如何更改网址并检测后退按钮 [英] How to change url and detect the back button
问题描述
我已经设置了一个页面,当你点击一个链接时,内容就会改变,而不会刷新页面,同样,这个URL与这个完全相同的命令(这就是它在代码中的形式)命令一样:
I've set up a page where when you click on a link the content changes without refreshing the page and so does the URL with this exact same command(that's how it's in the code) command:
window.history.pushState("object or string", "title", "/photo.php");
但是当用户点击后退按钮时,内容不会变回。我该怎么做?
我有这个想法,因为当你在脸书上点击主页上的图片,当你点击后退按钮(两次,我认为这是一个错误),你回到家里,网址变回,页面根本不刷新。
But when a user clicks on the back button the content doesn't change back. How can i do it? I have that in mind because when in facebook you click on a picture at the home page and when you click the back button(twice i think it's a bug) you get back to the home and the url changes back and the page doesn't refresh at all.
推荐答案
您可以使用 onpopstate
,就像这样。它也会在使用导航按钮时被触发。
You can use onpopstate
, like this. It will be fired when the navigation buttons are used, too.
window.onpopstate = function(e) { // executed when using the back button for example
alert("Current location: " + location.href); // location.href is current location
var data = e.state;
if(data) {
alert(JSON.stringify(e.state)); // additional data like your "object or string"
}
};
这篇关于如何更改网址并检测后退按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!