2011-04-18 49 views
2

我是新来的使用jQuery选项卡,我希望能够添加直接链接到特定选项卡的功能外。基本上所有的工作都很好,标签内容显示出来了,但实际的标签没有激活,但是当你点击它时,它就会显示出来。我为背景图片设置了标签。这是我的CSS看起来像为li元素添加一个活动类,如果链接有一个哈希标签,然后让li元素活动

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; 
    }); 
}); 

我想要实现的是如果URL中有一个特定的位置:../../#tab-1 设置里为主动,并显示出活跃状态李元素。

+0

此代码中的错误,我作为工作(我添加了样式'.tab_content {display:none;}'并创建了像'

this is tab 1
'这样的标签)。我注意到,如果我加载页面,然后手动将浏览器栏中的URL从#tab-1更改为#tab-2,然后按回车,它不显示标签2.但是,如果我复制并粘贴#tab-2 URL到一个新的浏览器窗口,它的工作原理。它也从书签起作用。 (顺便说一下,在这行末尾缺少一个分号:'location.hash = activeTab') – Jeff 2011-04-19 14:01:49

+0

从另一个页面直接链接到#tab-2时也有效。 – Jeff 2011-04-19 14:04:45

+0

感谢您的支持... – MRC 2011-04-19 16:01:16

回答

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 

而且,你有你的里面有(你忘了Concat的location.hach变量) 希望这有助于