使用javascript为多个元素设置属性



所以我有table:

<table class="checkout-list">
<thead>
<tr>
<th class="checkout-title">item</th>
<th class="checkout-title">amount</th>
<th class="checkout-title">total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
</tr>
<tr>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
</tr>
</tbody>
</table>

和javascript我想从thead tr th取值,并将它们设置为tbody tr td作为属性。我试过了:

let title = [];
document.querySelectorAll('.checkout-title').forEach(el => {
title.push(el.innerHTML);
});
document.querySelectorAll('.checkout-info').forEach((el, index) => {
el.setAttribute('data-title', title[index]);
});

总线,因为它是现在我只设法分配值给第一个tbody tr td子和第二个未定义的左,它看起来像这样:

<tbody>
<tr>
<td class="checkout-info" data-title="item"></td>
<td class="checkout-info" data-title="amount"></td>
<td class="checkout-info" data-title="total"></td>
</tr>
<tr>
<td class="checkout-info" data-title="undefined"></td>
<td class="checkout-info" data-title="undefined"></td>
<td class="checkout-info" data-title="undefined"></td>
</tr>
</tbody>

我应该如何修复这个未定义的赋值?

代码的问题是,querySelectordocument.querySelectorAll('.checkout-title')只有三个节点,querySelectordocument.querySelectorAll('.checkout-info')只有六个节点。这就是为什么前3个节点有值,后3个节点有undefined

你必须用title[index % header.length]title数组访问节点,这样它就会循环两次标题并正确分配属性

let title = [];
const header = document.querySelectorAll('.checkout-title');
header.forEach(el => {
title.push(el.innerHTML);
});
const nodes = document.querySelectorAll('.checkout-info');
nodes.forEach((el, index) => {
el.setAttribute('data-title', title[index % header.length]);
});
<table class="checkout-list">
<thead>
<tr>
<th class="checkout-title">item</th>
<th class="checkout-title">amount</th>
<th class="checkout-title">total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
</tr>
<tr class="delivery_price">
<td class="checkout-info"></td>
<td class="checkout-info"></td>
<td class="checkout-info"></td>
</tr>
</tbody>
</table>

最新更新