2013-07-30 122 views
0

好了,所以我一直停留在這一段時間。我已經看了教程,我不明白這是怎麼回事...工作如何動態地加載內容

This is the Site

我想將導航選項(如「主頁」「關於」「聯繫人」)加載到綠色內容框中。

下面的代碼:

<div id="header"> 
    <nav> 
    <ul> 
     <li><a href="content/home.html">Home</a></li> 
     <li><a href="about.php">About</a></li> 
     <li><a href="contact.php">Contact</a></li> 
    </ul> 
</nav> 
</div> 
<div id="banner"></div> 
    <div id="container"> 
    <div id="top"> 
    <div class="welcome">Welcome to HabShine</div> 
    </div> 
    <div id="content"> 
    <section id="main-content"> 
    <div id="guts"></div> 
    </div> 
    </section> 
    <div id="end"></div> 

而這裏的JavaScript的

$(function() { 

    var newHash  = "", 
     $mainContent = $("#main-content"), 
     $content = $("#content"), 
     baseHeight = 0, 
     $el; 

    $content.height($content.height()); 
    baseHeight = $content.height() - $mainContent.height(); 

    $("nav").delegate("a", "click", function() { 
     window.location.hash = $(this).attr("href"); 
     return false; 
    }); 

    $(window).bind('hashchange', function(){ 

     newHash = window.location.hash.substring(1); 

     if (newHash) { 
      $mainContent 
       .find("#guts") 
       .fadeOut(200, function() { 
        $mainContent.hide().load(newHash + " #guts", function() { 
         $mainContent.fadeIn(200, function() { 
          $content.animate({ 
           height: baseHeight + $mainContent.height() + "px" 
          }); 
         }); 
         $("nav a").removeClass("current"); 
         $("nav a[href="+newHash+"]").addClass("current"); 
        }); 
       }); 
     }; 

    }); 

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

}); 

這真的是越來越對我來說,我一直試圖最長做到這一點!如果有人有任何建議或解決方案,請幫助我!

+1

使用css導航 – Backtrack

回答

1

編輯:我已經添加了一個e.preventDefault()函數,因爲它在其他鏈接之後。其次,請看這個小提琴作爲演示,顯然目前沒有內容需要加載,但在Chrome或Firefox的控制檯中,您應該看到它嘗試加載正確的頁面。 http://jsfiddle.net/jqUxb/

您可以使用jQuery的.load()函數將頁面加載到div中。

所以,你的代碼看起來是這樣的:

$(document).ready(function(){ 
    $("nav").delegate("a", "click", function(e) { 
     e.preventDefault(); 
     var menuItem = $(this); 
     //remove "current" class 
     $("nav a").each(function(){ 
     $(this).removeClass("current"); 
     }) 
     //flag the current menu-item as current: 
     $(menuItem).addClass("current"); 
     //load the content: 
     $('#main-content').load($(menuItem).attr("href")); 

    }); 
}); 

本質上講,當你點擊鏈接,它就會抓住被點擊和Ajax負載從HREF內容到你的DIV的鏈接的href。

如果你想確保瀏覽器的歷史仍然有效,我建議你看看插件如jQuery地址

希望這有助於你。

+0

好吧我很困惑,我只是抓我現在有什麼用? –

+0

如果你只是想將一個頁面的內容加載到一個div中,說about.php我的代碼就足夠了。如果你想跟蹤我認爲你可能試圖實現的歷史,我會建議尋找一個jQuery的地址 – JanR

+0

是「這個」是一個變量,或者我將不得不用一些東西來代替它嗎? (抱歉,所有的新手問題,我只是真的失去了,當談到導航..我是新來的。) –