我有这个HTML代码
<div>
<div><input id="wpsl-search-input1"/></div>
<div><a id="wpsl-search-button1" href="#" target="_self">submit</a></div>
</div>
这个jquery
<script>
$('#wpsl-search-button1').click(function() {
var url = '/pages/location-search/?';
$('#wpsl-search-input1').each(function() {
url += 'zip=' + $(this).val() + "&";
});
window.location.replace(url);
});
</script>
但由于某种原因,它不起作用。有什么帮助吗?
答案 0 :(得分:8)
如果您只想重定向到输入中的url,请使用以下代码:
<script>
$('#wpsl-search-button1').click(function() {
var url = '/pages/location-search/?';
//you dont need the .each, because you are selecting by id
var inputURL = $('#wpsl-search-input1').val();
//Redirects
window.location.href = url + inputURL;
return false;
});
</script>
答案 1 :(得分:0)
尝试在加载DOM后执行它,如下所示:
<script>
$(function() {
$('#wpsl-search-button1').click(function() {
var url = '/pages/location-search/?';
$('wpsl-search-input1').each(function() {
url += 'zip=' + $(this).val() + "&";
});
window.location.replace(url);
});
});
</script>
答案 2 :(得分:0)
按ID选择元素时,需要一个井号:
$('#wpsl-search-input1')