如何在哈希位置更改时触发事件

How to trigger an event when hash location changes

我正在尝试使用方法 onhashchange 在我的 url 中更改哈希值时触发一个事件。我正在调用它,但它似乎从未被执行过。

我尝试了以下方法。

$(function () {
    window.addEventListener("onhashchange", function () {
        alert("Here");
    });

    window.onhashchange = function () {
        alert("Changed");
    }
)};

这些函数没有被调用有什么原因吗?

您应该在第一个示例中写 'hashchange' 而不是 'onhashchange'。

这段代码对我来说工作正常,至少在 Chrome:

window.addEventListener('hashchange', function(e){
    console.log('changed');
})

这是简短的代码片段: https://jsfiddle.net/bm8jjwmq/

if ("onhashchange" in window) {
    alert("The browser supports the hashchange event!");
}

▲ 支持 // ▼ 实施

function locationHashChanged() {
    if (location.hash === "#somecoolfeature") {
        somecoolfeature();
    }
}

window.onhashchange = locationHashChanged;

来源:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onhashchange