2011-09-07 51 views

回答

3

看一看this revision

我已經分解出來的代碼來顯示一個標籤到一個函數showTab

var showTab = function(id) { 
    $tab = $("#" + id); 
    $('.tabTrigger').removeClass('selectedTab'); 
    $tab.addClass('selectedTab'); 
    $('.tabContent').hide(); 
    $('#' + id.replace('tab','content')).show(); 
} 

其餘的則非常簡單:

// Show the selected tab, or the first one if none is selected 
var selectedId = $('.tabTrigger.selectedTab').attr('id'); 
showTab(selectedId || $('.tabTrigger:first').attr('id')); 

// Set up the click handlers 
$('.tabTrigger').click(function(){ 
    showTab(this.id); 
}); 

作爲一般的音符,在所有這些情況下,您需要將你想運行的代碼分解爲一個獨立的函數。一旦你這樣做,其餘的就自然而然了。

+0

非常感謝! – benhowdle89

+0

你並不需要將id傳入showTab。如果你只是調用'$('。tabTrigger')。click(showTab);'你可以在函數內部引用'this'。你可以使用不帶參數的'click()'來觸發'.selectedTab'上的事件,以便它被選中。 – Dennis

+0

@丹尼斯:這也是可以的。但我更喜歡這種方式,因爲您可以獨立於'click'處理程序使用'showTab'。 – Jon

0

嘗試$('.tabTrigger.selectedTab')的選擇,而不是,然後用.show()告訴他們:

$('.tabTrigger.selectedTab').show(); 

http://jsfiddle.net/mattlunn/4CtLV/1/

+0

但你也需要顯示相應的內容(如果它不是第一個') –

+0

但我需要證明對應於所選選項卡 – benhowdle89

+0

@ benhowdle89內容:在這種情況下,你的小提琴已經工作... http://jsfiddle.net/4CtLV/? – Matt

0

試試我的更新:http://jsfiddle.net/4CtLV/5/

$(document).ready(function() { 
    $('.tabContent:gt(0)').hide(); 
    $('.tabTrigger:first').addClass('selectedTab'); 
    var selectedTab = $('.tabTrigger.selectedTab:first'); 
    if (selectedTab.length == 1) { 
     $('#' + selectedTab.attr('id').replace('tab', 'content')).show(); 
    } 
    $('.tabTrigger').click(function() { 
     $('.tabTrigger').removeClass('selectedTab'); 
     $(this).addClass('selectedTab'); 
     $('.tabContent').hide(); 
     var id = $(this).attr('id'); 

     id = id.replace('tab', 'content'); 

     $('#' + id).show(); 
    }); 
});