2013-02-20 51 views
0

我在我的網站上設置了一個hashchange函數,它允許我在「about」頁面上的6個不同部分之間切換,這很好,它將哈希值附加到每個部分沒有問題。
但是我遇到的問題是當你從另一個頁面鏈接到這些散列時,它們無法加載相關內容,例如:www.thisisawebsite.com/about/#section03
散列工作正常,當你在關於頁面,但來自其他地方它只是加載section01。
jQuery:hashchange函數問題

jQuery(document).ready(function(){ 
jQuery('.about').hide(); 
jQuery('#section01').show(); 

jQuery(function(){ 
jQuery(window).on('hashchange', function(){ 
     var hash = window.location.hash; 
    jQuery('.sub-menu').each(function(){ 
      jQuery('.about').hide(); 
     if (jQuery(this).attr('hook') === hash.replace('#section', '')) { 
      jQuery('#section'+jQuery(this).attr('hook')).fadeIn(); 
      return false; 
     } 
    }); 

}); 
}); 
jQuery(window).trigger('hashchange'); 
}); 

這個問題能解決的整個想法跟我想用一個hashchange函數,所以我沒有必須有6個獨立的網頁,我可以只顯示/隱藏每節一個頁面和鏈接用哈希給他們。

回答

1

如果你加載了已經存在的散列標籤的頁面,窗口上的hashchange事件是否會觸發?如果它不存在你的問題,我會建議將每個循環重構爲一個單獨的函數,然後在文檔就緒時調用它來查看是否存在任何哈希標記,然後淡入內容。

像這樣的東西(我沒有試過,因爲我沒有你的DOM,但你會得到的想法。

jQuery(document).ready(function(){ 

    jQuery(window).on('hashchange', function(){ 
     var hashFound = determineContent(); 
     if(hashFound) return false; 
    }); 

    function determineContent(){ 

     var hash = window.location.hash; 
     jQuery('.about').hide(); 

     jQuery('.sub-menu').each(function(){ 

      if (jQuery(this).attr('hook') === hash.replace('#section', '')) { 
       jQuery('#section'+jQuery(this).attr('hook')).fadeIn(); 
       return true; 
      } 
     }); 

     // no hash found, so let's show #section01 
     jQuery('#section01').show(); 

     return false; 
    } 

    determineContent(); 
}); 

如果這不起作用,有一個偉大的插件只是這jQuery的,該處理AJAX事件也是如此。我一直在使用這個很多的JS基於Web的應用程序。

http://www.asual.com/jquery/address/

+0

是的,這是令人沮喪,因爲我想不通爲什麼它這樣做了。如果你在about頁面的哈希之間導航,並且你在#section03上說,我已經只刷新了頁面,並切換回#section01。奇怪是不是,上面的代碼也沒有工作? – user1374796 2013-02-20 10:06:13