javascript 窗口 onhashchange 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10577642/
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-26 10:19:35  来源:igfitidea点击:

Window onhashchange not working

javascriptjqueryhtmldom

提问by Question Overflow

I have a web page that contains two articles. Upon loading this page, jQuery is used to hide the two articles and slide down the first one. User can click on the navigation tab to view the second article. Then go back to the first article by clicking the back button using the onhashchangeevent. The following is my HTML code:

我有一个包含两篇文章的网页。加载此页面时,jQuery 用于隐藏两篇文章并向下滑动第一篇。用户可以单击导航选项卡查看第二篇文章。然后通过使用onhashchange事件单击后退按钮返回第一篇文章。以下是我的 HTML 代码:

<nav>
 <a href='#1'>Article 1</a>
 <a href='#2'>Article 2</a>
</nav>

<article id=1>
 The first article.
</article>

<article id=2>
 The second article.
</article>

And here is the javascript code:

这是 javascript 代码:

function change(hash)
{
 $('article:visible').slideUp();
 if(hash != '')
 {
  $(hash).slideDown();
 }
 else
 {
  $('article').first().slideDown();
 }
}

$('nav a').click(function(){
 var id = $(this).attr('href');
 change(id);
});

$('article').hide();
change(location.hash);
window.onhashchange = change(location.hash);

What was observed is that the page remains on the second article despite clicking the back button. I am using firefox 12.0 browser and don't know what is causing it not to work. Any help is appreciated. Thanks.

观察到的是,尽管单击了后退按钮,页面仍保留在第二篇文章上。我正在使用 firefox 12.0 浏览器,但不知道是什么导致它无法工作。任何帮助表示赞赏。谢谢。

回答by Joseph

You might want to try:

您可能想尝试:

window.onhashchange = change;

//and read location.hash in the change function instead
function change(){
    var hash = location.hash;
    ...
}

or

或者

window.onhashchange = function(){
    change(location.hash);
}


window.onhashchange = change(location.hash);

If my JS ain't rusty, this fails because

如果我的 JS 没有生锈,这将失败,因为

  • calls change()
  • functions that have no return return undefined
  • you are assigning undefinedto window.onhashchange- which is wrong because you're supposed to assign a functionto an event.
  • 电话 change()
  • 没有返回的函数返回 undefined
  • 您正在分配undefinedwindow.onhashchange- 这是错误的,因为您应该将 a 分配function给一个事件。