选择表行的更好方法

Better way for selecting table row?

本文关键字:更好 方法 选择      更新时间:2023-11-10

我有以下(简化的)表结构:

<table class="form-table">
<tbody>
<tr>
<tr><--Need to select and add class on this guy based on h3 class "check"-->
<th scope="row">
<h3 class="check">Default Checbox:</h3>
</th>
<td>
</tr>
</tbody>
</table>

所以我想在h3类"check"上面选择"table row"。表是动态生成的,所以我不能只使用:eq():gt():lt()

要选择这个家伙,我使用这个代码:

$('tbody tr').find('h3.check').parent().addClass('cool');
$('.cool').parent().addClass('until');

但问题是,为了做出选择,我给了一个不必要的课程"酷"。

<table class="form-table">
<tbody>    
<tr>
<tr>
<tr class="until"><--Class successfully added but..-->
<th class="cool" scope="row"><--An extra Class in order to select "table row"-->
<h3 class="check">Default Checbox:</h3>
</th>
<td>
</tr>
</tbody>
</table>

有没有更好的方法(不添加不必要的类)?

您可以使用.has()

$('tbody tr').has('h3.check').addClass('cool');

或:具有

$('tbody tr:(h3.check)').addClass('cool');