如何使用jquery获取文本并通过data attr为td设置值



我已经完成了这段代码

$('table td').each(function(index, element) {
        var th = $('table tr:first-child th').eq($(this).index()).text();
    $(this).attr('data-title', th);
});

我的问题是当我使用多表不工作。

<table style="width:100%">
  <tr>
    <th>title-1</th>
    <th>title-2</th>
  </tr>
  <tr>
    <td>ooo</td>
    <td>fds</td>
  </tr>
</table>
<table style="width:100%">
  <tr>
    <th>title-3</th>
    <th>title-4</th>
  </tr>
  <tr>
    <td>ooo</td>
    <td>fds</td>
  </tr>
</table>

有没有人能解决这个问题,我在上面给出了一些示例代码供参考

您的selector将运行document,将其限制为当前表,

$('table td').each(function(index, element) {
   var th = $(this).closest('table').find('tr:first-child th').eq($(this).index()).text();
   $(this).attr('data-title', th);
});
演示

使用基于$(this)的DOM遍历。

var th = $(this).closest("table").find("tr:first-child th").eq($(this).index()).text();

最新更新