窗口onhashchange不工作 [英] Window onhashchange not working
本文介绍了窗口onhashchange不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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屋!
查看全文