javascript 如果我直接打开带有哈希的页面,jQuery 的 hashchange 事件将不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20652020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:58:16  来源:igfitidea点击:

the hashchange event of jQuery doesn't work if I open a page with hash directly

javascriptjqueryhtml

提问by daisy

I placed a script tag at the end of a html page:

我在 html 页面的末尾放置了一个脚本标签:

$(window).on ('hashchange', function (e) { alert (location.hash); });

$(window).on ('hashchange', function (e) { alert (location.hash); });

It works if I click on buttons with hrefs like #a, but If I open links like localhost/aaa#athe alert function is not triggered.

如果我点击带有 href 的按钮,它会起作用#a,但是如果我打开链接,例如localhost/aaa#a不会触发警报功能。

So it looks like I have to detect the presence of a hash when the document is ready. But that looked wrong.

所以看起来我必须在文档准备好时检测散列的存在。但这看起来不对。

Is there a way to make it work in both situations?

有没有办法让它在这两种情况下都有效?

回答by Arun P Johny

You have to trigger the event manually on page load. The event will only get triggered when there is a direct action from the user. Since it is page load with no action from the user the on hashchange event will not get triggered.

您必须在页面加载时手动触发事件。只有当用户有直接操作时才会触发该事件。由于它是页面加载,用户没有任何操作,因此不会触发 on hashchange 事件。

$(window).on('hashchange', function (e) {
    alert(location.hash);
}).trigger('hashchange');

If you want to fire the event only when there is a hash value then

如果您只想在有哈希值时触发事件,那么

$(window).on('hashchange', function (e) {
    alert(location.hash);
});

if (window.location.hash) {
    $(window).trigger('hashchange')
}