窗口onhashchange不工作 [英] Window onhashchange not working

查看:74
本文介绍了窗口onhashchange不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < nav> 
< a href ='#1'>第1条< / a>
< a href ='#2'>第2条< / a>
< / nav>

< article id = 1>
第一篇文章。
< / article>

< article id = 2>
第二篇文章。
< / article>

这里是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);观察到的是,尽管点击了后退按钮,页面仍然保留在第二篇文章上。我正在使用firefox 12.0浏览器,不知道是什么导致它不工作。任何帮助是赞赏。谢谢。

解决方案

您可能想尝试:

  window.onhashchange = change; 

//并在更改函数中读取location.hash而不是
函数change(){
var hash = location.hash;
...
}

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






  window.onhashchange = change(location.hash); 

如果我的JS不生锈,则会失败,因为




  • 调用 change()

  • 没有返回结果的函数未定义

  • 您将未定义分配给 window.onhashchange - 这是错误的,因为您应该为事件分配一个函数


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 onhashchange event. The following is my HTML code:

<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:

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.

解决方案

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

  • calls change()
  • functions that have no return return undefined
  • you are assigning undefined to window.onhashchange - which is wrong because you're supposed to assign a function to an event.

这篇关于窗口onhashchange不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆