gpt4 book ai didi

jquery - 将 类附加到同一列中的

转载 作者:行者123 更新时间:2023-12-01 07:35:53 24 4
gpt4 key购买 nike

我已经在网上搜索了几个小时,但仍然无法弄清楚。

<table>  
<tr>
<th class="name">Name</th>
<th class="age">Age</th>
<th class="nick">Nick</th>
</tr>

<tr>
<td>John</td>
<td>30</td>
<td>Johnny</td>
</tr>

<tr>
<td>Robert</td>
<td>35</td>
<td>Bob</td>
</tr>
</table>

有没有办法将这些标题中的类附加到同一列中的 TD 标记?

最佳答案

我会这样做:

$("table th").each(function(i, val) {
var th = $(this);
var selector = "td:nth-child(" + (i+1) + ")";
th.parent().siblings().find(selector).attr("class", th.attr("class"));
});

它使用 :nth-child selector有效地获得相同的<td>在同一列中。但是,如果您使用 rowspan/colspan 元素,它就会崩溃。

注意:您必须向索引添加 1,因为 each() 上的索引是从零开始的,但是 :nth-child()是基于一的。

此外,您不能使用 :eq在此上下文中选择器,因为它仅匹配单个元素。

关于jquery - 将 <th> 类附加到同一列中的 <td>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1829508/

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