我使用以下方法更改与表单上的输入/下拉列表对应的查询URL参数。目前window.location.href
将导致更改页面重新加载。如何在不重新加载的情况下集成history.replaceState()
来修改URL?
REGEX功能
function replaceQueryString(url, param, value) {
var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
if (url.match(re))
return url.replace(re, '$1' + param + "=" + value + '$2');
else
return url + '&' + param + "=" + value;
}
输入更改
$("#input_field").on('change', function(e) {
window.location.href = replaceQueryString(window.location.href, 'input_value', $(this).val());
});
更新
我现在设法在更改时将网址更新为值domain.com/2
,但如何通过replaceQueryString
函数运行它以将其解析为domain.com/?input_value=2
$("#input_field").on('change', function(e) {
window.history.replaceState("#input_field", "input_value", $(this).val());
});
答案 0 :(得分:1)
将replaceQueryString()
函数传递给.replaceState()
window.history.replaceState({}
, "input_value"
, replaceQueryString(location.href, "input_value", $(this).val()));