首页 > 解决方案 > 如何使用 .each jQuery 获取 id 并为每个 jQuery 设置属性?

问题描述

我希望能够获取每个的 id<th>并将它们设置为每个<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++;

    });

但它根本不起作用。

有任何想法吗?

标签: jqueryhtml-table

解决方案


问题是这$('table tr td')将返回所有 tds,所以如果你有 2 行 4 个 tds,结果是 8 个 tds,并且 8 比你的计数大。您必须遍历每一行。

//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);
});


推荐阅读