如何查明历史 back/forward 是否被触发

How to find out if the history back/forward was triggered

我正在使用 ajax 模拟菜单。一切正常,但 backforward 按钮无法正常工作。

所以代码是:

$('#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 工作正常。但是当点击浏览器 back/forward 按钮时不应触发 pushingState 函数。

所以我的想法是创建一个 if 语句来检查是否单击了其中一个按钮。但是我没有找到类似的东西。这里有一些对我不起作用的链接:detect back button click in browser and JavaScript or jQuery browser back button click detector

也许我在这个方向上考虑的太多了,不知何故更容易?

添加了 pushingState 函数

function pushingState(href){
    if (href == "/about" || href == "/about/") {
        history.pushState('About', 'about', href);
    }
    if (href == "/creator" || href == "/creator/") {
        history.pushState('Creator', 'creator', href);
    }
}

我现在正在使用这段代码。它与最初的想法有点不同,仍然不是完美的解决方案,但至少更好,后退和前进按钮可以使用:

$('#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);
        }
    };
});