我有兩個(或更多)表與不同的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();
});
的解決方案,我有涉及表名的大量使用硬編碼。希望使代碼具有動態性。 – neelmeg