2011-04-08 141 views
0

我想使用jQuery構建基於錨的導航系統。我真的不想使用plugin like this作爲suggested here。任何人都可以幫助我建立像這樣的系統的基本邏輯?jQuery錨定導航

基本上我希望能夠有一個網頁成爲像這樣通過鏈接多個AJAX內容:

  • /myurl.html#state1
  • /myurl.html#state2

目前我只是結合的Click處理程序鏈接打開對話框等我然後可以將URL更改爲/myurl.html#state1。問題是,我這樣做,或者我只是讓<a>標籤自己指向該網址,然後使用jQuery來檢測URL何時發生變化,這意味着它也可以在頁面加載?

任何建議/想法將是巨大的 - 感謝

+4

我知道你可能不想使用插件,但我發現jquery-bbq是最好的這種功能http://benalman.com/projects/jquery- bbq-plugin/ – Calum 2011-04-08 11:37:56

+0

Sans插件,這將是使用http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/ – Calum 2011-04-08 11:40:21

+0

@Calum我發現燒烤之前,th anks的建議,它只是一個頁面,儘管如此插件似乎是矯枉過正。我之前也看到了yendesign的帖子,但我真的不喜歡設置計時器來檢查更改的想法 - 看起來很浪費 – Chris 2011-04-08 12:25:48

回答

2
<a href="#state1" rel="ajaxpage1.html"></a> 
<a href="#state2" rel="ajaxpage2.html"></a> 

$('a').each(function (i,obj){ 
    $(obj).click(function(){ 
     var url = $(obj).attr('rel'); 
     $..ajax({ 
      url: url, 
      success: function(){...}, 
      error : function(){...}// incase you get a 404, or 500 and so on.... 
     }); 
    }); 
}); 

$(document).ready(function(){ 
    //if you need it on refresh, or if a user got the link from another page 
    // it automatically will trigger the click therefore trigger the ajax 
    if(window.location.hash != '#'){ 
     $('a[href="'+window.location.hash+'"]').click(); 
    } 
}); 

我還是件事你應該使用插件,因爲他們有錯誤,並固定它們可能,所以你必須要測試你的事,浪費很多的時間,但你的電話:)