将搜索词插入 URL 无法正常工作
Inserting search term into URL not working properly
我在一家促销产品公司工作。他们的产品供应商给了我一个代码,可以在他们的网站上添加一个搜索框,用于搜索他们的产品数据库并显示结果。我对其进行了更改以满足我的需要,但我遇到了一个问题,即当您开始填写搜索框时,它会在按钮旁边显示 URL。知道如何解决这个问题吗?
我的搜索字段:
<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;
此行将 link href 作为文本内容放入 link 中。如果您不想要,请删除此行。
改变
link.search= '?searchTerms='+encodeURIComponent(input.value);
至
link.href= '?searchTerms='+encodeURIComponent(input.value);
这是附加 URL 文本:
link.firstChild.data= link.href;
删除或注释掉--或者使用上面Marcos的建议,这是更简单和更典型的解决方案。
我在一家促销产品公司工作。他们的产品供应商给了我一个代码,可以在他们的网站上添加一个搜索框,用于搜索他们的产品数据库并显示结果。我对其进行了更改以满足我的需要,但我遇到了一个问题,即当您开始填写搜索框时,它会在按钮旁边显示 URL。知道如何解决这个问题吗?
我的搜索字段:
<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;
此行将 link href 作为文本内容放入 link 中。如果您不想要,请删除此行。
改变
link.search= '?searchTerms='+encodeURIComponent(input.value);
至
link.href= '?searchTerms='+encodeURIComponent(input.value);
这是附加 URL 文本:
link.firstChild.data= link.href;
删除或注释掉--或者使用上面Marcos的建议,这是更简单和更典型的解决方案。