gpt4 book ai didi

javascript - 添加或更新查询字符串参数 - URL 保持不变

转载 作者:行者123 更新时间:2023-11-30 12:48:29 24 4
gpt4 key购买 nike

我正在使用这段代码来管理查询字符串参数:

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;
}
}

函数来源:add or update query string parameter

我正在调用该函数,一切运行正常,但我浏览器上的 url 没有改变。我还使用 Chrome 控制台检查函数是否被正确调用,函数是否正常并重新调整预期值,但 url 保持不变。

谢谢你的帮助

最佳答案

此函数不会更改 url。它只是返回一个字符串。

如果你想更改 url(重新加载页面),你应该这样写:

window.location.href = UpdateQueryString(your_key, your_value, your_url)

如果您想在不重新加载整个页面的情况下更改 url,使用 HTML5 History/State API,您可能对此感兴趣:

https://github.com/browserstate/history.js/

关于javascript - 添加或更新查询字符串参数 - URL 保持不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21784134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com