我在一家促销产品公司工作。他们的产品供应商给了我一个代码,让我在他们的网站上添加一个搜索框,该搜索框搜索他们的产品数据库并显示结果。我更改了它以满足我的需求,但是我遇到了一个问题,当您开始填写搜索框时,它会在按钮旁边显示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>
Javascript将搜索词插入URL中:
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?带有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 会自动转换查询字符串参数。
link.firstChild.data= link.href;
此行将链接 href 作为文本内容放在链接内。如果您不希望这样,请删除此行。
更改
link.search= '?searchTerms='+encodeURIComponent(input.value);
自
link.href= '?searchTerms='+encodeURIComponent(input.value);
附加URL文本:
link.firstChild.data= link.href;
删除它或注释掉它 - 或者使用上面Marcos的建议,这是一个更简单,更典型的解决方案。