【问题标题】:HTML: How to create search bar?HTML:如何创建搜索栏?
【发布时间】:2014-12-20 23:46:22
【问题描述】:

我有这个搜索栏:

<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>

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

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

【问题讨论】:

标签: javascript html search


【解决方案1】:

你可以用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>

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

<input type="text" class="tftextinput" id="tftextinput" name="q" size="21" maxlength="120">

我真的不明白你为什么要这样做,因为处理这个请求服务器端要困难得多,因为它只是处理你在进行标准表单传输时将收到的 $_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>

【讨论】:

  • 你好,它不起作用。我添加了 javascript 和 id="tftextinput" 但它不起作用
  • @ban 我忘了写 e.preventDefault 。直接放在window.location.href...行前面...
  • 你可以为我发布完整的代码吗?我不能让它工作
  • 我已经贴在上面了! @禁止
猜你喜欢
  • 2023-02-20
  • 1970-01-01
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多