javascript - 如何引用另一个元素的数据属性?

标签 javascript php html css

我正在尝试创建一个响应式表格,它可以从水平布局折叠到垂直布局。为此,我使用了一个 :before 伪元素,它从数据属性中获取它的值。考虑以下 dom 结构:

td:before {
      content: attr(data-th);
    }
<table>
      <thead>
        <tr>
          <th>First</th>
          <th>Second</th>
          <th>Third</th>
          <th>Fourth</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td data-th="First">Alpha</td>
          <td data-th="Second">Beta</td>
          <td data-th="Third">Gamma</td>
          <td data-th="Fourth">AnotherGreekLetter</td>
        </tr>
      </tbody>
</table>



    

这工作得很好,直到您意识到,您必须手动编写每个数据属性,因为每个新数据行都需要数据属性。

理想情况下我想要这样的东西:

td:before:nth-of-type(4n+1) {
      content: attr(data-th:nth-of-type(4n+1));
}
    
    td:before:nth-of-type(4n+2) {
      content: attr(data-th:nth-of-type(4n+2));
}
<table>
      <thead>
        <tr>
          <th data-th="First">First</th>
          <th data-th="Second">Second</th>
          <th data-th="Third">Third</th>
          <th data-th="Fourth">Fourth</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Alpha</td>
          <td>Beta</td>
          <td>Gamma</td>
          <td>AnotherGreekLetter</td>
        </tr>
      </tbody>
</table>

    

我在这里引用了 th 节点的数据属性。 现在,据我所知,没有办法只用 css 遍历 dom-tree,所以我认为这只有用 javascript 才有可能。然而,我从未使用过数据属性,所以我希望我是错的。

我可以使用(按偏好降序排列):仅 css、php、javascript 来实现吗?

最佳答案

不要认为你可以通过 CSS 做到这一点,如果你也使用 jQuery,你可能会使用稍微不同的方法,因为你可以使用 ID 从标题中找到值并将其写到正文中,例如

<table>
  <thead>
    <tr data-id="1">
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
    </tr>
  </thead>
  <tbody>
    <tr data-id="1"></tr>
  </tbody>
</table>

还有 jQuery:

$(document).ready(function() {
    $("thead tr th").each(function( index ) {
      $("tbody tr[data-id='" + $(this).parent().attr('data-id') + "']").append('<td>' + $(this).text() + '</td>');      
    });
});

http://codepen.io/anon/pen/kXdkyY

希望这能为您提供另一种想法,让您了解如何以不同的方式遍历和获取数据。

关于javascript - 如何引用另一个元素的数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078883/

相关文章:

php - 变量的单数或复数设置。 PHP

php - 如何在 PHP 中为数组预分配内存?

php - 如何在从数据库中获取字符串以在 FPDF 上查看时打断

ios - 所有浏览器和平台中的 HTML5 和视频捕获可能性

html - 在居中表格旁边放置图像

javascript - 当我告诉输入字段不要清除文本时,它正在清除文本

javascript - 更改页面时如何清理和卸载 Unity WebGL Canvas

javascript - Node.JS:为什么嵌套的 Promise then 似乎乱序了?

html - 如何使用边框图像和线性渐变模拟基本投影?

javascript - 如何将原型(prototype)添加到对象