2014-02-09 126 views
0

我是jQuery的新手,並不知道我在做什麼。我需要一些幫助。jquery鏈接和URL哈希

我正在創建一個web應用程序。它有一個我想留在每一頁上的頁眉和頁腳,所以我決定使用jQuery將頁面加載到主內容div中,因此每次單擊鏈接時都不會重新加載整個頁面。

這裏是我用來實現這一目標是什麼:

<script> 
    $(function() { 
     $("a.ajax-link").on("click", function(e) { 
      e.preventDefault(); 
      $("#main_content").fadeOut('fast'); 
      $("#main_content").load(this.href); 
      $('html, body').animate({ scrollTop: 0 }, 0); 
      $("#main_content").fadeIn('fast'); 
     }); 
    }); 
    </script> 

每一個環節:

<a class="ajax-link" id="add" href="add.php"><span class="glyphicon glyphicon-plus-sign" style="margin-top:4px;"></span><div>add</div></a> 

這除了網頁地址的偉大工程。我的應用程序使用PHP,我需要能夠將PHP Header添加到像'index.php#about'這樣的頁面,該頁面將加載index.php頁面並在#main_content div中顯示about.php。

我嘗試這樣做:

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var id = window.location.hash; 
     $(id).trigger('click'); 
    }) 
    </script> 

我可以看到該鏈接被選中(周圍框),但它實際上並沒有點擊它。我不知道爲什麼。

非常感謝您的幫助!

+0

查找到。孩子(),.removeClass(),.addClass() – mattsven

回答

0

我認爲你可以得到散列,添加一個PHP擴展,並進行ajax調用。

<script> 
    $(function() { 
     $("a.ajax-link").on("click", function(e) { 
      e.preventDefault(); 

      // Get the hash from the URL and append .php extension 
      // index.php#about ==> 'about.php' 

      var page = window.location.hash + ".php"; 

      //Make an ajax call using the page variable. 

      $("#main_content").fadeOut('fast'); 
      $("#main_content").load(page); 
      $('html, body').animate({ scrollTop: 0 }, 0); 
      $("#main_content").fadeIn('fast'); 
     }); 
    }); 
</script> 
+0

謝謝您的幫助!我試過這個,它和之前做的一樣。我可以在瀏覽器選擇的鏈接附近看到一個框,但它沒有被點擊。 –