【问题标题】:Inserting search term into URL not working properly将搜索词插入 URL 无法正常工作
【发布时间】:2016-01-14 16:37:16
【问题描述】:

我在一家促销产品公司工作。他们的产品供应商给了我一个代码,可以在他们的网站上添加一个搜索框,用于搜索他们的产品数据库并显示结果。我对其进行了更改以满足我的需要,但我遇到了一个问题,当您开始填写搜索框时,它会在按钮旁边显示 URL。知道如何解决这个问题吗?

JS Fiddle

我的搜索栏:

<input id="searchTerms" name="searchTerms" type="text" 
       placeholder="Search all Products" />
<a id="reflectedlink" href="http://321987-1d1.espwebsite.com/ProductResults/" 
   onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click', 'Search Button']);">
  <button>Search</button>
</a>

将搜索词插入 URL 的 Javascript:

var link = document.getElementById('reflectedlink');
var input = document.getElementById('searchTerms');
input.onchange=input.onkeyup = function() {
  link.search = '?searchTerms='+encodeURIComponent(input.value);
  link.firstChild.data = link.href;
};

【问题讨论】:

    标签: javascript dynamic-url


    【解决方案1】:

    为什么要为此使用 javascript?带有 GET 方法的原生 HTML 表单会自动为您生成:

    <form method="GET" action="http://321987-1d1.espwebsite.com/ProductResults/">
       <input id="searchTerms" name="searchTerms" type="text" placeholder="Search all Products" />
       <button type="submit" onclick="_gaq.push(['_trackEvent', 'Homepage', 'Click', 'Search Button']);">Search</button> 
    </form>
    

    在您按下提交按钮的那一刻,URL 会自动使用查询字符串参数进行转换。

    【讨论】:

    • 提供给我的是 JS 版本。我选择不把它弄得太乱,因为我对它了解得不够多。不过这很好用。谢谢。
    【解决方案2】:
    link.firstChild.data= link.href;
    

    这一行将链接href作为文本内容放入链接中。如果您不想这样,请删除此行。

    【讨论】:

      【解决方案3】:

      改变

      link.search= '?searchTerms='+encodeURIComponent(input.value);

      到

      link.href= '?searchTerms='+encodeURIComponent(input.value);

      【讨论】:

        【解决方案4】:

        这是附加 URL 文本:

        link.firstChild.data= link.href;
        

        删除它或将其注释掉——或者使用上面 Marcos 的建议,这是一种更简单、更典型的解决方案。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-02
          • 1970-01-01
          • 1970-01-01
          • 2019-08-04
          • 2021-11-10
          • 2017-01-28
          • 2013-12-23
          • 2015-07-27
          相关资源
          最近更新 更多