阻止window.onhashchange在通过JavaScript设置哈希时执行 [英] prevent window.onhashchange from executing when hash is set via JavaScript
问题描述
当用户更改页面的哈希值时,我使用window.onhashchange函数执行代码:
I use the window.onhashchange function to execute code when the User changes the hash of the page:
window.onhashchange = function() { /* do something */ };
在某些函数中,我还通过JavaScript设置哈希:
In some functions I also set the hash via JavaScript:
window.location.hash = "#abc";
我想通过JavaScript设置哈希时阻止触发onhashchange事件。
I want to prevent the onhashchange event from firing when I set the hash via JavaScript.
到目前为止我尝试了什么:
What I have tried so far:
var currently_setting_hash = false;
window.onhashchange = function() {
if (currently_setting_hash)
return;
//...
}
currently_setting_hash = true;
window.location.hash = "#abc";
currently_setting_hash = false;
这不起作用,因为事件被延迟触发,所以代码将首先设置hash,然后将currently_setting_hash设置为false,然后执行onhashchange事件。
That didn't work because the event is fired with a delay, so the code will first set the hash, then set "currently_setting_hash" to false and then execute the onhashchange event.
任何想法如何实现?或者有没有办法检测哈希是由用户还是通过JavaScript设置的?
Any ideas how this could be accomplished? Or maybe is there a way to detect if the hash was set by the user or via JavaScript?
推荐答案
你可以重置变量来自事件处理程序本身:
You could reset the variable from the event handler itself:
var currently_setting_hash = false;
$(window).on("hashchange", function() {
if (currently_setting_hash) {
currently_setting_hash = false;
return;
}
currently_setting_hash = false;
//...
});
currently_setting_hash = true;
window.location.hash = "#abc";
这篇关于阻止window.onhashchange在通过JavaScript设置哈希时执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!