2011-10-08 79 views
1

我有以下的jQuery代碼,允許我使用製表符,以在內容/ div之間回退和第四。我的問題是使用下面的代碼,我怎麼能根據url中的變量加載最初的選項卡?所以,如果我去默認TAB2負載somesite.com/page.php#tab2的則不用TAB1裝載:jquery - 通過網址選擇標籤

$('.tabcontent > div').hide(); 
$('.tabcontent > div:first-child').show(); 
$('.tabs > li:first-child').addClass('selected'); 
$('.tabs > li a').click(function() { 
    var tab_id = $(this).attr('href'); 
    $(tab_id).parent().children().hide(); 
    $(tab_id).fadeIn(); 
    $(this).parent().parent().children().removeClass('selected'); 
    $(this).parent().addClass('selected'); 
    return false; 
}); 

編輯

只是要注意這個代碼是一個click事件,但是如果我想通過網址更改選項卡,那麼它不會工作,除非他們單擊一個選項卡。那麼,我該如何獲得它來傾聽點擊,並聽取當前網址中是否有值?

回答

2

您可以使用GUP功能,發現here

function gup(name) 
{ 
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); 
    var regexS = "[\\?&]"+name+"=([^&#]*)"; 
    var regex = new RegExp(regexS); 
    var results = regex.exec(window.location.href); 
    if(results == null) 
    return ""; 
    else 
    return results[1]; 
} 

這將允許你讀取URL參數,並用它來導航到所選擇的選項卡。

0

希望這將有助於: -

var tab_id = $(this).attr('href'); 
var split = tab_id.split('#'); 
    split = split[1]; 

if (split = "page 2") { 

window.alert(split); 

} else { 
// Default condition 

} 

JS小提琴例在這裏 - http://jsfiddle.net/aNMBW/

0

檢測的網址片段(#whatever)的變化是很難做到跨瀏覽器沒有一點幫助。我通常使用本Alman的燒烤插件:

http://benalman.com/code/projects/jquery-bbq/examples/fragment-jquery-ui-tabs/

如果我誤解,你只是想設置基於初始URL加載選項卡,你可以做它通過檢測哈希:

... 
if(window.location.hash){ 
    $(".tabs > li a[href=" + window.location.hash + "]").click(); 
} 

這是假設你的標籤被鏈接到HREF =「#富」,那你訪問的網址是mysite.com/pagename#foo

0

你可以在使用window.location.hash一個URL的哈希值。從那裏,你只需要做一些小的檢查來確定應該顯示哪個標籤。

Here's a live example。請注意,我們實際上不能在jsFiddle中使用window.location.hash,因爲它使用iFrames,這意味着您在瀏覽器地址欄中看到的地址不是代碼本身會獲得的值。因此,只需在代碼中直接設置hash變量的值,即可玩轉它。

無論如何,假設這是你的HTML:

<div>One</div> 
<div>Two</div> 
<div>Three</div> 

那麼你的JavaScript是:

$(function(){ 

    hash = window.location.hash 

    index = parseInt(hash.replace('tab','')) - 1; 

    if(isNaN(index)){ //if the hash isn't a valid tab 
     index = 0; 
    } 

    $('div').eq(index).show(); 
}); 

你應該也可能先檢查一下,確保$('div').eq(index)實際存在,訴諸表示第一如果它沒有(就像我們做散列分析不會產生合法的值)那樣。