2011-04-18 31 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變量) 希望這有助於