HTML:如何创建搜索栏?

Ban*_*Ban 2 html javascript search

我有这个搜索栏:

<div id="tfheader">
    <form id="tfnewsearch" method="get" action="http://mywebsite.com">
            <input type="text" class="tftextinput" name="q" size="21" maxlength="120"><input type="submit" value="search" class="tfbutton">
    </form>
<div class="tfclear"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但是当我搜索“关键字”时,它会重定向到http://mywebsite.com/?q=keyword

如何重定向到http://mywebsite.com/keyword?非常感谢 !

chr*_*con 5

你可以用javascript来做

<script>
var a = document.getElementById('tfnewsearch');
a.addEventListener('submit',function(e) {
e.preventDefault();
var b = document.getElementById('tftextinput').value;
window.location.href = 'http://mywebsite.com/'+b;

});

</script>
Run Code Online (Sandbox Code Playgroud)

并为您的输入字段提供一个名为 tftextinput 的 ID。

<input type="text" class="tftextinput" id="tftextinput" name="q" size="21" maxlength="120">
Run Code Online (Sandbox Code Playgroud)

我真的不明白您为什么要这样做,因为处理这个请求服务器端要困难得多,因为它会简单地处理您在进行标准表单传输时将收到的 $_GET 数据。

编辑:

这是完整的代码:

<div id="tfheader">
    <form id="tfnewsearch" method="get" action="http://www.mywebsite.com">
        <input type="text" class="tftextinput" id="tftextinput" name="q" size="21" maxlength="120"><input type="submit" value="search" class="tfbutton">
    </form>
<div class="tfclear"></div>
</div>

<script>
    var a = document.getElementById('tfnewsearch');
    a.addEventListener('submit',function(e) {
        e.preventDefault();
        var b = document.getElementById('tftextinput').value;
        window.location.href = 'http://mywebsite.com/'+b;

    });

</script>
Run Code Online (Sandbox Code Playgroud)