我有一個菜單,在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沒有散列時 –