gpt4 book ai didi

javascript - 在使用 onPopState 和 pushState 时,我应该使用什么 js 来处理后退按钮点击

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:57 25 4
gpt4 key购买 nike

我正在使用 pushState 更改网站的 url:

history.pushState("", "info", "/info");

效果很好,但现在后退按钮不起作用。我相信我需要使用 onPopState 编写我自己的后退和前进按钮行为,它通过历史堆栈并呈现适当的页面。诀窍在于,当“后退”为 Null 时,它应该执行后退按钮通常会执行的操作(在用户进入我的网站之前“返回”页面)。

这似乎是非常标准的行为,是否有我可以使用的配方/一些标准代码?

最佳答案

啊,我想出了一个解决方案,没有我想象的那么难(基本上它只是使用 url 路径名来呈现正确的东西):

// Makes the back button work
window.onpopstate = function(event) {
if (document.location.pathname == '/main') {
$("#main").show();
$("#info").hide();
$("#settings").hide();
}
if (document.location.pathname == '/info') {
alert('info');
$("#main").hide();
$("#info").show();
$("#settings").hide();
}
if (document.location.pathname == '/settings') {
alert('settings');
$("#main").hide();
$("#info").hide();
$("#settings").show();
}
};

关于javascript - 在使用 onPopState 和 pushState 时,我应该使用什么 js 来处理后退按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4664056/

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