我有一个菜单,在div中加载一个新的html文件。加载是通过附加到菜单的<a>
标签的点击事件完成的。加载效果很好,我通过用哈希标记构造新的href将新的加载添加到历史记录中。Javascript:历史记录未加载页面
但是,当我使用后退按钮时,URL在浏览器地址栏中更新正确,但页面从不加载。如果我关注地址栏并按下输入它加载。
这是位于mypage.html标题中的JavaScript。
<script type="text/javascript">
$(document).ready(function() {
// replace menu link click
$(".right-menu a").live('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
window.location.href = $(this).attr('href');
$("#content-right").load('mypage'+window.location.hash.substring(1)+'.html');
return false;
});
// If page loads, load the content area according to the hash.
var hrtag = window.location.hash.substring(1);
if(hrtag=="")
hrtag='about';
$("#content-right").load('mypage'+hrtag+'.html');
window.location.hash = hrtag;
});
</script>
这是菜单
<ul class="right-menu">
<li><a href="mypage.html#about">About</a></li>
<li><a href="mypage.html#screens">Screens</a></li>
<li><a href="mypage.html#license">License</a></li>
<li><a href="mypage.html#download">Download</a></li>
<li><a href="mypage.html#donate">Donate</a></li>
</ul>
如果我加载页面为mypage.html
,JavaScript的附加散列#about
,如果我点击菜单与mypageabout.html
加载DIV ID "content-right"
,例如下载,它将加载div ID "content-right"
与mypagedownload.html
在这两种情况下,window.location
将设置为散列版本的页面,mypage.html#about
和mypage.html#download
将其注册到历史记录中。
如果我按以下顺序点击菜单; 许可证,约,屏幕然后单击浏览器的后退按钮,地址栏将显示; mypage.html#about
,mypage.html#license
但它不会加载页面!?!
这些URL显然是在历史记录中,但它们不会加载。 有什么线索可能是错误的吗?
//感谢
编辑 - 该解决方案
由于安德烈斯·加洛的文章中,我想出了这个解决方案:
<script type="text/javascript">
$(document).ready(function() {
// Make sure the page always load #about
LoadIDWithURL('#content-right','myPageAbout.html');
window.addEventListener('hashchange',function() {
if (window.location.hash != "") {
// We have a hash, use it!
LoadIDWithURL('#content-right','MyPage'+window.location.hash.substring(1)+'.html');
} else {
// We do not have a hash, force page reload!
window.history.go(0);
}
});
});
// Load the targetID with the URL loadURL.
function LoadIDWithURL(targetID,loadURL) {
$(targetID).load(loadURL);
}
</script>
你的文章做到了。我不得不通过调用'window.history.go(0);'来添加一个特殊情况,当URL没有散列时 –