javascript jquery 发布和重定向 onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24045951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery post and redirect onclick
提问by Leo Leoncio
I have this html code
我有这个 html 代码
<div>
<div><input id="wpsl-search-input1"/></div>
<div><a id="wpsl-search-button1" href="#" target="_self">submit</a></div>
</div>
And this jquery
还有这个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>
But for some reason it doesn't work. Any help ?
但由于某种原因它不起作用。有什么帮助吗?
回答by Nano
Let me try to explain to you what you did and what you need to do to make your code work in the way you intended.
让我尝试向您解释您做了什么以及您需要做什么才能使您的代码按您预期的方式工作。
<script>
$('#wpsl-search-button1') // jQuery method to retrieve an element with the ID "wpsl-search-button1"
.click(function() { // Attach a "click" listener to the element
var url = '/pages/location-search/?'; // Declare a variable with the name "url" containing a string "/pages/location-search/?"
$('#wpsl-search-input1') // retrieving the element with the id "wpsl-search-input1"
.each(function() { // looping over all elements found by the id selector (ID's are unique, so the query above should always return one jQuery element. No need for a loop here)
url += 'zip=' + $(this).val() + "&"; // append a "zip" parameter with the value of the found element (this is refering to the current element of the iteration -> the input)
});
window.location.replace(url); // replace the current resource with the one in the "url" variable
});
</script>
If you just want to redirect to a url based by the input value use this code:
如果您只想根据输入值重定向到 url,请使用以下代码:
<script>
$('#wpsl-search-button1').click(function() { // you dont need the .each, because you are selecting by id
var inputURL = $('#wpsl-search-input1').val();
window.location.href = `/pages/location-search/?zip=${inputURL}`; // Redirecting to the passed url (also working relative to the current URL)
return false; // Cheap way to call the "event.preventDefault()" method
});
</script>
回答by eordano
Try executing it after the DOM has loaded, like this:
尝试在 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>
回答by circusdei
When selecting an element by id, you need a pound sign:
按 id 选择元素时,需要一个井号:
$('#wpsl-search-input1')