javascript history.pushState() 更改查询值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10420955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:49:23  来源:igfitidea点击:

history.pushState() change query values

javascriptjquerypushstate

提问by Grigor

If I have a link that is being changed with the function history.pushState({}, "", link);where my linkis for example page.php?value=1&value2=2Is there a way to just change the value2with pushState()function instead of changing the whole link?

如果我有一个正在使用history.pushState({}, "", link);我所在的函数更改的链接,link例如page.php?value=1&value2=2有没有办法只更改value2withpushState()函数而不是更改整个链接?

采纳答案by devstruck

If what you're trying to do is change the URL without adding an additional entry to the history object, you might try replaceState.

如果您尝试做的是更改 URL 而不向历史记录对象添加其他条目,您可以尝试replaceState.

history.replaceState({value: 1, value2: X}, "title", "page.php");

回答by Chris Pratt

No, because the query string is part of the URL. If you don't truly need to pass those values for the purposes of the server, you can include them in the history's state object itself, and then you can change just the state object with pushState(). For example:

不,因为查询字符串是 URL 的一部分。如果您真的不需要为服务器传递这些值,您可以将它们包含在历史记录的状态对象本身中,然后您可以使用pushState(). 例如:

history.pushState({value: 1, value2: 2}, "Title", 'page.php');
history.pushState({value: 1, value2: 'new value'}, "Title");

回答by ChrisThompson

You can use this useful function to change a query string parameter value:

您可以使用这个有用的函数来更改查询字符串参数值:

function updateParam(url, param, value)
{  
    var re = new RegExp(param+"(.+?)(&|$)","g");

    return url.replace(re, param+'='+value)  
}