Javascript 添加或更新查询字符串参数-URL保持不变
我使用这段代码来管理查询字符串参数:Javascript 添加或更新查询字符串参数-URL保持不变,javascript,Javascript,我使用这段代码来管理查询字符串参数: function UpdateQueryString(key, value, url) { if (!url) url = window.location.href; var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"); if (re.test(url)) { if (typeof value !== 'undefined' &a
function UpdateQueryString(key, value, url) {
if (!url) url = window.location.href;
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null)
return url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
var hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
}
else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?',
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null)
url += '#' + hash[1];
return url;
}
else
return url;
}
}
功能来源:
我正在调用函数,一切正常,但我浏览器上的url没有更改。我还使用Chrome控制台检查函数调用是否正确,函数是否正常,并重新运行预期值,但url保持不变
感谢您的帮助重点是此功能不会更改url,您应该自己执行,如:
window.location.href = UpdateQueryString("yourkey","newvalue");
或者将其更改为:
function UpdateQueryString(key, value, url) {
//this flag is to check if you want to change the current page url
var iscurrentpage = false;
if (!url){
url = window.location.href;
iscurrentpage = true;
}
var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi");
//this variable would be used as the result for this function
var result = null;
if (re.test(url)) {
if (typeof value !== 'undefined' && value !== null) result = url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
var hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null) url += '#' + hash[1];
result = url;
}
} else {
if (typeof value !== 'undefined' && value !== null) {
var separator = url.indexOf('?') !== -1 ? '&' : '?',
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null) url += '#' + hash[1];
result = url;
} else result = url;
}
//if this is current page update the current page url
if(iscurrentpage) window.location.href = result;
return result;
}
然后不使用url参数调用它,只使用2个参数:
UpdateQueryString("yourkey", "newvalue");
此函数不会更改url。它只是返回一个字符串 如果你想更改url(重新加载页面),你应该这样写:
window.location.href = UpdateQueryString(your_key, your_value, your_url)
如果您想使用HTML5历史/状态API更改url而不重新加载整个页面,您可能会对以下内容感兴趣:
没错。这就是我所需要的,不需要像你说的那样重新加载页面。谢谢