-1

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

JS小提琴

我的搜索字段:

<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;
};
4

4 回答 4

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

于 2016-01-14T16:40:34.877 回答
0
link.firstChild.data= link.href;

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

于 2016-01-14T16:41:06.850 回答
0

改变

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

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

于 2016-01-14T16:43:36.593 回答
0

这是附加 URL 文本:

link.firstChild.data= link.href;

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

于 2016-01-14T16:54:23.473 回答