2012-06-20 42 views
1

我有兩個(或更多)表與不同的ID和類名在每個表內是相同的。根據點擊的範圍,我想顯示或隱藏tbody內的行。例如:如果span class =「quarter」被點擊,我想在tbody中顯示class =「quarter」的行並隱藏class =「month」。我應該使用jQuery事件監聽器來實現嗎?我希望這段代碼能夠被id = tab3或tab4等許多其他表所使用。所以我不想使用$(「#tab1」)onclick ...我希望能夠檢測哪個表在哪個表中被點擊,然後顯示其中的tbody元素。jquery事件偵聽器動態檢測點擊嗎?

<table id="tab1"> 
<thead><tr><th><span class="quarter">Quarter</span></th></tr> 
<tr><th><span class="month">Month</span></th></tr> 
</thead> 
<tbody> 
<tr class="quarter"><td></td></tr> 
<tr class="month"><td></td></tr> 
</tbody> 
</table> 

<table id="tab2"> 
<thead><tr><th><span class="quarter">Quarter</span></th></tr> 
<tr><th><span class="month">Month</span></th></tr> 

最終解決方案(我的實際HTML結構從上面的例子有點不同)

$('table thead span label').click(function() { 
         $("label:not(this.className)").css('color','#d6c9b9');  
         $(this).css('color','#00425f');   
         $(this).parents('table').parents('table').find('table').hide();      
         $(this).closest('table').find('tbody tr').hide(); 
         $(this).closest('table').show();       
         $(this).closest('table').find('tbody tr.' + this.className).show(); 
         $(this).parents('table').parents('table').find('table.'+ this.className).show(); 
      }); 
+0

的解決方案,我有涉及表名的大量使用硬編碼。希望使代碼具有動態性。 – neelmeg

回答

1

試試這個:

$('span').click(function(){ 
    $(this).closest('table').find('tbody tr').hide(); 
    $(this).closest('table').find('tr.' + this.className).show(); 
}) 
+0

我建議使用'var c = this.className',因爲在那行代碼中不需要jQuery,或者更好,只需使用'$(this).closest('table')。find('tr。 '+ this.className).show()'根本不使用'var c'。 – jfriend00

+0

不錯!不知道$ .closest(); +1 – Sparkup

+0

@ jfriend00感謝您的建議。 – undefined

0

事情是這樣的:

$('.toggle thead tr').click(function(){ 
    var c = $(this).find('span').attr('class'); 
     p = $(this).parent().parent(); 
    p.find('tbody tr').hide(); 
    p.find('tbody .' + c).show(); 
}); 

<table id="tab1" class="toggle"> 
... 
</table> 

DEMO:here

1
$('table thead span').click(function() { 
    $(this) 
     .closest('table') // find parent table 
     .find('tbody tr.' + this.className) // detect row with same class name 
     .show() // show that row 
     .siblings('tr') // capture other tr 
     .hide(); // hide those tr 
}); 

DEMO