如果链接具有哈希标记,则将活动类添加到li元素,然后使li元素处于活动状态

时间:2011-04-18 20:54:32

标签: jquery

我刚开始使用jQuery标签,我希望能够从外部添加直接链接到特定标签的功能。基本上一切都工作正常,标签内容显示但实际标签不会激活,但是当你点击它时,它会显示出来。我为标签设置了背景图像。这就是我的CSS看起来像

ul.tabs li a.tab-1 {background-position:0 0;}
ul.tabs li a.tab-1:hover {background-position:0 -61px;}
ul.tabs li.active a.tab-1 {background-position:0 -125px;}

当您从外部来源发送到链接时,不显示活动类。

<ul class="tabs">
  <li class="active"><a class="tab-1" href="#tab-1">history</a></li>
  <li><a class="tab-2" href="#tab-2">About</a></li>
</ul>

以下是jQuery代码的其余部分:

$(document).ready(function() {
  //Default Action
  $(".tab_content").hide(); //Hide all content
  if(location.hash != "") {
    /* If there is a tab id in the page URL */
    $(location.hash).show(); //Show tab content
    $('ul.tabs li:has(a[href="location.hash"])').addClass("active").show(); //Activate tab
    $(this).find("a").addClass("active"); //Add "active” class to href inside selected 
  } else {
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
  }
  //On Click Event
  $("ul.tabs li").click(function() {
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(this).addClass("active"); //Add "active" class to selected tab
    $(".tab_content").hide(); //Hide all tab content
    var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab content
    location.hash = activeTab //Add the anchor to the url (for refresh)
    $(activeTab).fadeIn(); //Fade in the active ID content
    return false;
  });
});

我想要实现的是网址是否具有特定位置:../../#tab-1 将li设置为active并显示li元素的活动状态。

1 个答案:

答案 0 :(得分:0)

您可以模拟点击事件:

$(document).ready(function() {
  //create tab widget before the following code is executed
  $(".tab_content").hide(); //Hide all content
  if(location.hash != "") {
    $(location.hash).show(); //Show tab content
    $('ul.tabs li:has(a[href="'+location.hash+'"])').click(); //LINE CHANGED
  } else {
    $("ul.tabs li:first").click(); //LINE CHANGED
  }
... your code continues here

另外,你的内部有一个错误(你忘了连接location.hach变量) 希望这有帮助