我有以下代码
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块之后。我的控制台输出验证了这个
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
我在这里遗漏了什么或者发生了什么事吗? 有没有办法绕过这个?
答案 0 :(得分:1)
让我们将代码简化为
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);