如何使用 .each jQuery 获取 id <th> 并为每个 id <td> 设置属性?



我希望能够获取每个<th>的 id,并将它们设置为表每个<td>的数据属性。

以前:

<table>
<tr>
<th id="1"><th>
<th id="2"><th>
</tr>
<tr>
<td><td>
<td><td>
</tr>
<tr>
<td><td>
<td><td>
</tr>
...
</table>

后:

<table>
<tr>
<th id="1"><th>
<th id="2"><th>
</tr>
<tr>
<td data="1"><td>
<td data="2"><td>
</tr>
<tr>
<td data="1"><td>
<td data="2"><td>
</tr>
...
</table>

到目前为止,我有这个jQuery:

array = $('table th').map(function(){
return this.id;
});
i = 0;
$('table tr td').each(function() {
$(this).attr('data-title', array[i]);
i++;
});

但它根本不起作用。

有什么想法吗?

问题是$('table tr td')将返回所有 tds,因此如果您有 2 行 4 个 td,则结果为 8 tds,而 8 大于您的第 th 计数。 您必须遍历每一行。

//loop over each row
$('table tr').each(function() {
//use the index of the td in the row for the array
$(this).find('td').each(function(index){
$(this).attr('data-title', array[index]);
});
});
//or as an alternative
array.each(function(index, id){
$('table tr td:nth-child('+ (index + 1) +')').attr('data-title', id);
});

最新更新