2012-09-02 246 views
0

我有一個菜單,在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#aboutmypage.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> 

回答

1

我寫了這個確切的主題非常詳細的文章。它說明了如何建立正是你正在嘗試做的。

而且我的文章還介紹瞭如何通過在鏈接參數的JavaScript做特別的東西

下面是文章http://andresgallo.com/2012/06/08/ajaxifying-the-web-the-easy-way/

最好的方法是將您的功能附加到hashchanges鏈接而不是單擊事件。這允許歷史記錄中的任何更改利用您的JavaScript功能。

+0

你的文章做到了。我不得不通過調用'window.history.go(0);'來添加一個特殊情況,當URL沒有散列時 –

1

這是正常的行爲,不同網頁間導航時只在他們的散列。你有兩個選擇:

  1. 使用hashchange事件,或它的一個仿真,當用戶通過導航改變了哈希後退或前進,以檢測和更新頁面適當
  2. 使用HTML5 history API。
1

,你可以嘗試用hashchange

$(function(){ 
    $(window).hashchange(function(){ 
     // some event 
    }) 
})