将搜索字词插入网址无法正常使用

时间:2016-01-14 16:37:16

标签: javascript dynamic-url

我正在为促销产品公司工作。他们的产品供应商给了我一个代码,在他们的网站上添加一个搜索框,搜索他们的产品数据库并显示结果。我改变了它以满足我的需要,但是我遇到了一个问题,当你开始填写搜索框时,它会显示按钮旁边的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>

将搜索字词插入网址的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;
};

4 个答案:

答案 0 :(得分:0)

为什么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会自动使用查询字符串参数进行转换。

答案 1 :(得分:0)

link.firstChild.data= link.href;

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

答案 2 :(得分:0)

变化

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

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

答案 3 :(得分:0)

这是附加网址文字:

link.firstChild.data= link.href;

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