2011-02-12 48 views
3

我想知道是否有可能让脚本检测URL锚点,并加载特定于该锚点的内容。举例来说,我有这行代码:使用Jquery检测锚点?

<a href="#home"><span id="homeMenu">Home</span></a>

这行代码监听该代码:

$("#homeMenu").click(function() { 
    $("#home_content").show("slow"); 
    $("#accommodations_content").hide("slow"); 
    }); 

我怎么可能使它的是,如果用户访问http://www.myurl.com/home.html#home它加载了家庭内容自动。这也适用于我想实现的所有其他锚。

我想要这个,因为现在,如果用户直接访问任何锚点,没有任何锚点,它总是会显示主页。那么,有没有办法检测哪个URL被加载,然后运行脚本?

编辑

因此,目前只加载的住宿(在#Home即使)

当前代码:

<script type="text/javascript"> 
      $(document).ready(function() { 
      document.getElementById("javascriptCheck").style.visibility = 'hidden'; 
      $("#menu").load("snippets/menu.html"); 
      $("#locationMenu").load("snippets/locationMenu.html"); 
      $("#home_content").load("snippets/home_content.html"); 
      $("#accommodations_content").load("snippets/accommodations.html"); 
      $("#history").load("snippets/history.html"); 
      $("#footer").load("snippets/footer.html"); 

      var hash = window.location.hash; 
      if (hash = "#Home") { 
       $("#home_content").show("slow"); 
       $("#accommodations_content").hide("slow"); 
      } 
      if (hash = "#Accommodations") { 
       $("#accommodations_content").show("slow"); 
       $("#home_content").hide("slow");  
      } 
      }); 
     </script> 

回答

9

你必须检查在页面加载哈希标签。

使用此代码:

var identifier = window.location.hash; //gets everything after the hashtag i.e. #home 

if (identifier === "#home") { 
    $("#home_content").show("slow"); 
    $("#accommodations_content").hide("slow"); 
} 
+0

由于某种原因,我在使用此代码时遇到了问题。它究竟应该去哪里? – Johannes 2011-02-12 23:50:58

5

我猜,你想是这样的:jQuery hashchange plugin。它允许你对哈希的变化做出反应,并通过AJAX加载其他内容 - 但你也可以做其他的事情。用户甚至可以使用浏览器的后退按钮转到以前的状态。