繁体   English   中英

将 th 的文本添加到该列中 td 中的数据属性

[英]Add the text of the th to a data attribute in the td in that column

我需要使一些内容动态化,因此每次写入<th>的内容(如“名称”)时,该内容都存储在 var 中并归因于<td>的 data-th 属性,但这必须以正确的顺序进行。 所以: <th scope="col">Color</th>有内容“Color”,假设它是第二个子元素,每个<tr>的第二个<td>子元素应该有:
<td data-th="Color">Lorem Ipsum</td>

这是我要创建的输出:

<div class="table-color-bg fake-table-bg">
  <table class="fake-table fake-table-simple table">
    <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Company</th>
        <th scope="col">Description</th>
      </tr>
      </thead>
      <tbody>
        <tr>
          <td data-th="Name">Lorem Ipsum</td>
          <td data-th="Company">Lorem Ipsum</td>
          <td data-th="Description">Lorem Ipsum</td>
        </tr>
        <tr>
          <td data-th="Name">Lorem Ipsum</td>
          <td data-th="Company">Lorem Ipsum</td>
          <td data-th="Description">Lorem Ipsum</td>
        </tr>
        <tr>
          <td data-th="Name">Lorem Ipsum</td>
          <td data-th="Company">Lorem Ipsum</td>
          <td data-th="Description">Lorem Ipsum</td>
        </tr>
    </tbody>
  </table>
</div>

首先,您需要一个与此类似的脚本(使用jQuery库):

$('th').on('update-column', function() {
    var index = $(this).index();
    var value = $(this).text();

    $('td').eq(index).data(value);
});

其次,每次你都会改变<th>的内容。 您应该触发update-column事件,例如:

var th = $(th).eq(1);
th.text('Color');
th.trigger('update-column');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM