首页 > 解决方案 > 使用 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>

我应该如何解决这个未定义的分配?

标签: javascripthtml

解决方案


代码的问题是,只有三个节点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>


推荐阅读