我希望您能够在不刷新页面的情况下替换URL。
我需要更改的是:
我需要更改的是:
https://example.com/en/step1
至
https://example.com/en/step2
怎样做那件事?
https://example.com/en/step1
至
https://example.com/en/step2
怎样做那件事?
更新
根据操作浏览器历史记录,将空字符串作为pushState
方法的第二个参数(也称为标题)是安全的,可以防止未来对该方法的更改,因此最好像这样使用pushState
:
history.pushState(null, '', '/en/step2');
您可以在提到的文章中阅读更多相关信息。
原始回答:
使用history.pushState
,如下所示:
history.pushState(null, null, '/en/step2');
更新2回答 Idan Dagan的评论:
为什么不使用
history.replaceState()
?
来自 MDN
history.replaceState()
的作用与history.pushState()
完全相同,只是 replaceState() 修改当前的历史记录条目而不是创建一个新的。
这意味着如果你使用replaceState
,URL会被改变但用户无法再使用浏览器的“后退”按钮返回到以前的状态(因为replaceState
不会添加新的历史记录条目),这不建议使用,会产生不好的用户体验。
更新3添加window.onpopstate
因此,既然这个答案引起了你的注意,这里提供关于操作浏览器历史记录的额外信息。在使用pushState
后,你可以通过像这样使用window.onpopstate
检测后退/前进按钮导航:
window.onpopstate = function(e) {
// ...
};
pushState
的第一个参数是一个对象,如果您传递了一个 null
而不是一个 object
,则您可以在 onpopstate
中访问该对象,这非常方便。以下是方法:window.onpopstate = function(e) {
if(e.state) {
console.log(e.state);
}
};
更新4,增加读取当前状态:
当您的页面加载时,可能会有非空状态对象,您可以使用history.state
属性读取当前历史记录条目的状态,而无需等待popstate
事件,如下所示:
console.log(history.state);
奖励:使用以下内容检查history.pushState
支持:
if (history.pushState) {
// \o/
}
当你使用一个函数时,你需要考虑以下几个方面:
<p onclick="update_url('/en/step2');">Link</p>
<script>
function update_url(url) {
history.pushState(null, null, url);
}
</script>