在下面的表单中,我更改了 action 属性并提交了表单。那很好用。发生的事情是:如果当前位置是 http://localhost/search/?mod=all
并且搜索词是 14,则操作将更改为 http://localhost/search/?mod=all&handle=14
浏览器中的 url 也是如此。
但下次我尝试搜索时,因为现在的 url 是 http://localhost/search/?mod=all&handle=14
,我得到 http://localhost/搜索/?mod=all&handle=14&handle=15
。它会随着每个搜索词继续进行下去。
知道如何通过这一切保留原始 url http://localhost/search/?mod=all
吗?
这是表格:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
这是jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
最佳答案
有几种方法可以做到这一点。我宁愿不弄乱 window.location 并做一些更简单的事情:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
关于javascript - 在这种情况下使用 jquery 获取原始 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14109234/