2012-06-20 43 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