我正在尝试使用jQuery添加一个“bg-info”类,以便在带有子项的奇数tr之后的tr中添加>儿童班的“考试”。当带有子项的tr>时,应该停止应用“bg-info”类。看到“测试”的子类,然后继续应用下一个带有孩子的奇数tr>儿童班的“考试”见过。金额是动态的,因此它不能依赖于特定数量的tr。我尝试了很多组合,但似乎无法使其正常工作。见JSFiddle。在此先感谢:)
的jsfiddle
https://jsfiddle.net/vrpuahue/4/
HTML
<table>
<thead>
<tr>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="test">Test1</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test2</div>
</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test3</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test4</div>
</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test5</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
</tbody>
</table>
CSS
.bg-info {
background: grey;
}
JS
$('tbody tr td .test:odd').parent().parent().addClass('bg-info');
答案 0 :(得分:1)
在这种情况下,使用nextUntil方法可以帮助您。
我向所有偶数和奇数父母添加一个类,然后highlight
添加所需的特定元素。
<强> demo 强>
$('.test:odd').parents('tr').addClass('odd');
$('.test:even').parents('tr').addClass('even');
$('.odd').nextUntil('.even').addClass('highlight');
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="test">Test1</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test2</div>
</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test3</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test4</div>
</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>Highlight</td>
</tr>
<tr>
<td>
<div class="test">Test5</div>
</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
<tr>
<td>Do Not Highlight</td>
</tr>
</tbody>
</table>