我正在尝试创建一个响应式表格,它可以从水平布局折叠到垂直布局。为此,我使用了一个 :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/