【问题标题】:show multiple values from the data array in multiple HTML table elements with JavaScript使用 JavaScript 在多个 HTML 表格元素中显示数据数组中的多个值
【发布时间】:2022-01-28 00:10:33
【问题描述】:

我想一次在多个 HTML 表格元素中显示数据数组中的多个值。并且数据值会发生变化,需要用 HTML 覆盖。我通过使用嵌套的forEach 尝试了类似下面的操作,但它不起作用。我该怎么办?

我试过appendchild,但它会随着数据值的更新而创建新的单元格,我不想要它。

HTML

<table>
  <thead>something</thead>
  <tbody>
    <tr id="changeThis">
      <th>row head</th>
      <td>0</td><!-- 1 -->
      <td>0</td><!-- 2 -->
      <td>0</td><!-- 3 -->
      <td>0</td><!-- 4 -->
    </tr>
  </tbody>
</table>

js

const data = [1, 2, 3, 4]
const changeThis = document.querySelector("#changeThis");

changeThis.forEach(cellItem => {
   data.forEach(dataItem => {
      cellItem.innerHTML = dataItem
   })
})

感谢您的帮助!

【问题讨论】:

  • 您的意思是appendChild 而不是appendchild

标签: javascript arrays sorting


【解决方案1】:

您可以使用querySelectorAll 选择所有 td 并添加您的内容

const data = [1, 2, 3, 4]
const changeThis = document.querySelectorAll("#changeThis td");


changeThis.forEach((cellItem,idx) => {
      cellItem.innerHTML = data[idx];
})
<table>
  <thead>something</thead>
  <tbody>
    <tr id="changeThis">
      <th>row head</th>
      <td>0</td><!-- 1 -->
      <td>0</td><!-- 2 -->
      <td>0</td><!-- 3 -->
      <td>0</td><!-- 4 -->
    </tr>
  </tbody>
</table>

【讨论】:

    【解决方案2】:

    你也可以这样做......

    const 
      data       = [1, 2, 3, 4]
    , changeThis = document.querySelector('#changeThis')
      ;
    let index = 0;
    
    for (let cell of [...changeThis.cells])
      {
      if ( cell.matches('td'))
         cell.textContent = data[index++]
      }
    <table>
      <thead>something</thead>
      <tbody>
        <tr id="changeThis">
          <th>row head</th>
          <td>0</td><!-- 1 -->
          <td>0</td><!-- 2 -->
          <td>0</td><!-- 3 -->
          <td>0</td><!-- 4 -->
        </tr>
      </tbody>
    </table>

    【讨论】:

      猜你喜欢
      • 2017-09-18
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2022-07-26
      • 2019-02-22
      • 2021-11-12
      相关资源
      最近更新 更多