我的标记
<table class="table--responsive">
<thead>
<tr>
<th class="table--responsive__row-1">Header 1</th>
<th class="table--responsive__row-2">Header 2</th>
<th class="table--responsive__row-3">Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="table--responsive__row-1">blah blah
<span></span>
</td>
<td class="table--responsive__row-2">blah blah
<span></span>
</td>
<td class="table--responsive__row-3">blah blah
<span></span>
</td>
</tr>
<tr>
<td class="table--responsive__row-1">blah blah
<span></span>
</td>
<td class="table--responsive__row-2">blah blah
<span></span>
</td>
<td class="table--responsive__row-3">blah blah
<span></span>
</td>
</tr>
</tbody>
</table>
我需要做的是遍历<td>
中的每个<tbody>
,并在<th>
中找到相应的类。对于可能有多少<th>
没有限制。它可以是2到理论上的任何地方。
找到与<th>
对应的类的<td>
后,我需要在相应的<th>
中删除该文本并将其插入到<span>
元素中相应的<td>
。
所以我的标记最终应该是这样的:
<table class="table--responsive">
<thead>
<tr>
<th class="table--responsive__row-1">Header 1</th>
<th class="table--responsive__row-2">Header 2</th>
<th class="table--responsive__row-3">Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="table--responsive__row-1">blah blah
<span>Header 1</span>
</td>
<td class="table--responsive__row-2">blah blah
<span>Header 2</span>
</td>
<td class="table--responsive__row-3">blah blah
<span>Header 3</span>
</td>
</tr>
<tr>
<td class="table--responsive__row-1">blah blah
<span>Header 1</span>
</td>
<td class="table--responsive__row-2">blah blah
<span>Header 2</span>
</td>
<td class="table--responsive__row-3">blah blah
<span>Header 3</span>
</td>
</tr>
</tbody>
</table>
我需要代码能够循环遍历未知数量的类table--responsive__row-[i]
模式。
非常感谢任何协助。
答案 0 :(得分:0)
假设您使用的是jQuery
。
$('table>tbody>tr>td').each(function () {
let $td = $(this);
let className = $td.attr('class') ? $td.attr('class').split(' ')[0] : ''; // getting the first class on the `td`, else use a regexp to find the desired class name
let $th = $(`table>thead>tr>th.${className}`);
let text = $th.text();
let $span = $(this).find('span');
$span.text(text);
});
迭代所有tr
tr
选择所有$('table>tbody>tr>td');
。each
函数迭代它们。td
$(this).att('class')
上的课程
th
在课程中找到$('table>thead>tr>th.${className}')
。text
从头部获取$th.text()
。span
td
内找到$(this).find('span')
text
span
上设置$span.text(text)
醇>
答案 1 :(得分:0)
我正在做这部分jQuery部分伪代码,所以请原谅语法捷径。
var thKeyVal = [];
$('th').foreach(function() {
thKeyVal[$(this).attr('class')] = $this.text()
}
$('td').foreach(function() {
$(this).val = thKeyVal[$(this).attr('class')]
}
简而言之,循环并收集密钥:th
元素的值。然后遍历td
元素并在匹配键控数组时赋值。