javascript - 使用 javascript 为多个元素设置属性
问题描述
所以我有表:
<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>
我应该如何解决这个未定义的分配?
解决方案
代码的问题是,只有三个节点querySelector
document.querySelectorAll('.checkout-title')
和六个节点querySelector
document.querySelectorAll('.checkout-info')
。这就是前 3 个节点和undefined
后 3 个节点有价值的原因。
您必须从title
数组访问节点,title[index % header.length]
以便它循环两次标题并正确分配属性
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>
推荐阅读
- local-storage - 使用 Chrome / Firefox devtools 检查其他站点的 LocalStorage
- bash - 提取键/对字符串中键的值
- arduino - 如何在 ESP32 运行时更改 WIFI 凭据?
- git - 无法提交到 Github,获取提交未通过 EasyCLA 测试
- vue.js - 隐藏和显示组件
- python - df.update() 或 df.fillna() 不能将数据框中的 NaN 值替换为另一个数据框值
- c# - 在使用 GraphQL.client 使用 API 时添加内容类型标头
- crystal-reports - Crystal Report:删除 excel 中空的多余行详细信息部分
- discord.py - on_raw_reaction_add 不适用于 ctx 及其属性“作者”
- apache-spark - 使用 spark-submit 将数据加载到 SQL Server 时的 Parquet 列问题