gpt4 book ai didi

javascript - 如何使用 jquery 突出显示基于文本的表格列?

转载 作者:行者123 更新时间:2023-11-30 14:04:45 25 4
gpt4 key购买 nike

假设我有下表:

<table width=200 border=1>
<tr>
<th>Ignore</th>
<th>Highlight</th>
<th>Ignore</th>
</tr>
<tr>
<td>yep</td>
<td>yep</td>
<td>yep</td>
</tr>
<tr>
<td>yep</td>
<td>yep</td>
<td>yep</td>
</tr>
</table>

我想突出显示所有突出显示 列。我如何根据标题文本执行此操作?

我意识到这可以通过选择第 n 个 child 来实现,但 future 如何证明它不会发生列顺序更改。

$('body > table > tbody > tr > td:nth-child(2)').css('background-color', 'pink');

http://jsfiddle.net/8XSLF/

最佳答案

您需要获取具有高亮 文本的th 的索引。所以使用 :contains()选择器选择它然后使用 .index()找到它的索引。最后,选择每个 thtd 的索引等于找到的索引。

请注意,:contains() 选择器还会选择元素包含不需要的文本,例如 HighlightedText Highlighted。如果您的表格文本不固定,请使用 .filter()相反。

var i = $("table th:contains('Highlight')").index();
$("table tr th, table tr td").filter(function(){
return $(this).index() == i;
}).css("background", "pink");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width=200 border=1>
<tr>
<th>Ignore</th>
<th>Highlight</th>
<th>Ignore</th>
</tr>
<tr>
<td>yep</td>
<td>yep</td>
<td>yep</td>
</tr>
<tr>
<td>yep</td>
<td>yep</td>
<td>yep</td>
</tr>
</table>

关于javascript - 如何使用 jquery 突出显示基于文本的表格列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com