我使用ajax来模拟菜单。一切都很好,但后退和前进按钮并不完美。
所以代码是:
$('#sdt_menu a').on('click', function (e) {
href = $(this).attr("href");
e.preventDefault();
window.onpopstate = function (event) {
document.url = event.state.url;
loadSpecificPage(window.location.pathname);
};
pushingState(href);
})
window.onpopstate
查找历史记录中的更改。
pushingState
只是将新页面推送到历史记录中。
使用此菜单项可以正确加载到浏览器历史记录中。但是当我按下后退按钮时,会触发window.onpopstate
以及我的pushingState
功能。所以,让我们在第1页上说我现在加载第2页。当我在浏览器中点击后退按钮时,我正确地返回到第1页,但我重新加载第1页并转到它。所以最后我没有正确回去。因此,pushingState
函数不会被触发,那么它应该正常工作。我至少只用当前的方式用当前页面替换了当前页面。
摘要:window.onpopstate
正常运作。但是,当按下浏览器后退/前进按钮时,不会触发pushingState
功能。
所以我的想法是创建一个if语句来检查是否单击了其中一个按钮。但我没有找到类似的东西。这里有一些对我不起作用的链接:detect back button click in browser和JavaScript or jQuery browser back button click detector
也许我在这个方向上思考得太厉害了,而且某种程度上更容易?
function pushingState(href){
if (href == "/about" || href == "/about/") {
history.pushState('About', 'about', href);
}
if (href == "/creator" || href == "/creator/") {
history.pushState('Creator', 'creator', href);
}
}
答案 0 :(得分:2)
我现在正在使用这段代码。它与最初的想法略有不同,仍然不是完美的解决方案,但至少更好,后退和前进按钮正在工作:
$('#sdt_menu a').on('click', function (e) {
var href = $(this).attr("href");
history.pushState(href, '', href);
e.preventDefault();
window.onpopstate = function (event) {
if (event.state != null){
document.url = event.state.url;
pushingState(event.state);
}
};
});