我有以下代码
console.info('checking if url contains hash');
if (!location.hash) {
console.warn('if-block replacing hash to empty!');
location.href = '#';
// Running route() to trigger Router.otherwise()
console.info('running route() from if-block(hash doesn\'t exist)');
route(location.hash.slice(1));
} else {
// URL contains a hash. Running Router.when() to load template
console.info('running route() from else-block(hash already present in url)');
route(location.hash.slice(1));
}
// Bind hashchange-event to window-object... duh
console.info('binding hashchange event');
$(window).on('hashchange', function () {
console.info('running route() from hashchange');
route(location.hash.slice(1));
});
显然,事件监听器附加在 else-if block 之后。我的控制台输出验证了这一点
2015-02-13 12:51:14.281 main.js:69 checking if url contains hash
2015-02-13 12:51:14.284 main.js:71 if-block replacing hash to empty!
2015-02-13 12:51:14.290 main.js:75 running route() from if-block(hash doesn\'t exist)
2015-02-13 12:51:16.677 main.js:84 binding hashchange event
2015-02-13 12:51:16.678 main.js:86 running route() from hashchange
看起来事件监听器以某种方式获取了之前触发的 hashchange 事件。
仅当网址为 example.com
而不是 example.com/#
时才会发生这种情况。如果您进入网站时网址中缺少 /
或 /#
,则会触发此现象。
编辑:我遇到的问题是 hashchange
事件监听器在监听哈希更改之前就被触发。我想知道这是否正常。
另一个编辑:
一个更清晰的示例显示,当我第一次运行 getEventListeners(window)
时,没有监听器附加到 hashchange
事件。尽管如此,当我添加事件监听器时,它会拾取之前触发的 hashchange
我是否遗漏了一些东西或者发生了什么?
有什么办法可以绕过这个吗?
最佳答案
让我们将代码简化为
location.hash = 'foobar';
window.onhashchange = function() {
document.body.innerHTML = 'You should not see me. But you do :(';
};
要解决此问题,您可以使用 setTimeout
延迟添加事件处理程序:
location.hash = 'foobar';
setTimeout(function(){ // Delayed code
window.onhashchange = function() {
document.body.innerHTML = 'You should not see me. And you do not :)';
};
}, 0);
关于javascript - Hashchange 事件监听器在事件处理程序附加到事件之前监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28499538/