2012-10-31 62 views
3

我有一個功能WordPress主題,通過ajax加載內容。我遇到的一個問題是,當頁面直接加載時,ajax腳本不再起作用。例如,鏈接結構的工作原理如下,在www.example.com上點擊關於頁面鏈接,鏈接將變成www.example.com/#/about。但是,當我直接加載獨立頁面www.example.com/about時,從此頁面單擊的其他鏈接變爲www.example.com/about/#/otherlinks。我從這個tutuorial http://www.deluxeblogtips.com/2010/05/how-to-ajaxify-wordpress-theme.html修改了一些代碼。這是我的代碼。謝謝您的幫助。ajax加載URL hashchange問​​題

jQuery(document).ready(function($) { 
var $mainContent = $("#container"), 
    siteUrl = "http://" + top.location.host.toString(), 
    url = ''; 

$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() { 
    location.hash = this.pathname; 
    return false; 
}); 

$(window).bind('hashchange', function(){ 
    url = window.location.hash.substring(1); 

    if (!url) { 
     return; 
    } 

url = url + " #ajaxContent"; 

    $mainContent.fadeOut(function() { 
     $mainContent.load(url,function(){ 
      $mainContent.fadeIn(); 
     });   
     }); 
    }); 

    $(window).trigger('hashchange'); 

}); 

回答

2

你表達的問題不容易解決。有危在旦夕多種因素,但它歸結爲:

  • 到URL的任何更改將觸發頁面重載
  • 唯一的例外是,如果只是URL的散列部改變

正如你所看到的那樣,URL www.example.com/about/中沒有哈希部分。因此,這部分不能被腳本改變,否則會觸發頁面重新加載。
瞭解這一事實後,您的腳本只會通過添加新的哈希部分或修改現有哈希部分來更改URL,而不必單獨使用URL的「路徑名」部分。因此,您可以獲取www.example.com/about/#/otherlinks等網址。

現在,從我的角度來看,有兩種方法可以解決您的問題。

首先,有一個API that can modify the whole URL pathame without reload,但it's not available everywhere。使用此解決方案並回到舊版瀏覽器的經典頁面重新加載是cleaner method

否則,您可以強制重新加載頁面一次,將URL重置爲www.example.com/並從良好的基礎開始。這裏是這樣做的代碼:

$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]))", "click", function() { 
    location = location.assign('#' + this.pathname); 
    return false; 
}); 

應該指出,如果您的網站不在路徑名的根目錄下,這個腳本將不起作用。因此,要使其適用於www.example.com/mysite/,您需要更改正則表達式。

請讓我知道它是如何去的。

+0

感謝您的迴應,這些鏈接非常棒,我會告訴你它是如何結束的。 –

+0

如果這篇文章回答了您的問題,您可能需要通過單擊複選標記將其標記爲正確。謝謝〜 – hazerd

+0

我結束了與history.js去擺脫所有的hashchanges –