jquery发布和重定向onclick

Leo*_*cio 2 javascript jquery post window.location

我有这个HTML代码

<div>
 <div><input id="wpsl-search-input1"/></div>
 <div><a id="wpsl-search-button1" href="#" target="_self">submit</a></div>
</div>
Run Code Online (Sandbox Code Playgroud)

这个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>
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,它不起作用.有帮助吗?

Nan*_*ano 8

如果您只想重定向到输入中的url,请使用以下代码:

<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>
Run Code Online (Sandbox Code Playgroud)