动态检测点击的jquery事件监听器?

动态检测点击的jquery事件监听器?,jquery,addeventlistener,Jquery,Addeventlistener,我有两个(或更多)具有不同ID的表,每个表中的类名都相同。根据单击的范围,我希望显示或隐藏tbody中的行。例如:如果单击span class=“quarter”,我想在tbody中显示class=“quarter”的行,并隐藏class=“month”。我应该使用jQuery事件侦听器来实现这一点吗?我希望这段代码能够恢复到id=tab3或tab4的许多其他表,可能还有更多的表。因此,我不想使用$(“#tab1”)。onclick…我希望能够检测单击表的范围,然后显示其中的tbody元素 &l

我有两个(或更多)具有不同ID的表,每个表中的类名都相同。根据单击的范围,我希望显示或隐藏tbody中的行。例如:如果单击span class=“quarter”,我想在tbody中显示class=“quarter”的行,并隐藏class=“month”。我应该使用jQuery事件侦听器来实现这一点吗?我希望这段代码能够恢复到id=tab3或tab4的许多其他表,可能还有更多的表。因此,我不想使用$(“#tab1”)。onclick…我希望能够检测单击表的范围,然后显示其中的tbody元素

<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>
试试这个:

$('span').click(function(){
   $(this).closest('table').find('tbody tr').hide();
   $(this).closest('table').find('tr.' + this.className).show();
})
大概是这样的:

$('.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>
$('.toggle thead tr')。单击(函数(){
var c=$(this.find('span').attr('class');
p=$(this.parent().parent();
p、 查找('tbody tr').hide();
p、 find('tbody.'+c).show();
});
...
演示:


我的解决方案涉及大量使用硬编码的表名。希望使代码动态化。我建议使用
var c=this.className
,因为在这行代码中不需要jQuery,或者更好,只需使用
$(this.closest('table')。find('tr.+this.className)。show()
,而不使用
var c
。很好!不知道有关$.closest()的信息+1让每个跨距侦听一个单击事件可能会导致其他任何意外的最近表行出现问题?我的html结构比上面给出的示例稍微复杂一点。下面的代码从你的答案中获得灵感,帮助我实现了正确的功能
$('.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>
$('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
});