history.pushState() change query values

左心房为你撑大大i 提交于 2019-11-27 06:06:39

问题


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


回答1:


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

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



回答2:


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:

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



回答3:


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


来源:https://stackoverflow.com/questions/10420955/history-pushstate-change-query-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!