【问题标题】:Javascript Access to Only Header, Body or Footer Rows One at a TimeJavascript 一次只能访问一个页眉、正文或页脚行
【发布时间】:2022-11-29 07:40:17
【问题描述】:

我需要单独遍历(使用 javascript)每个表行的部分。这意味着我需要先遍历 THEAD 行,然后是 TBODY 行,最后是 TFOOT 行。

我需要做的事情比仅仅为方框着色要复杂得多,但出于本示例的目的,我只是尝试将 thead 行着色为红色,将 tbody 行着色为绿色,将 tfoot 行着色为黄色。如果我能让这些循环为每个部分的行工作,我就可以从那里接手完成其余的编码。

我试过下面的但它不起作用(它告诉我“行未定义”)。有人可以修复 ColorBoxes() 函数代码来让它工作吗?请不要在这里给我 CSS 答案,因为那不能解决问题——我需要遍历每个部分的行。谢谢!

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
}
</style>
<script language='javascript'>
function ColorBoxes()
{
   var tbl = document.getElementById('MyTable');
   for (var nRow = 0; nRow < tbl.tHead[0].rows; nRow++)
   {
     tbl.tHead[0].row[nRow].style.backgroundColor = 'red';
   }
   for (var nRow = 0; nRow < tbl.tBody[0].rows; nRow++)
   {
     tbl.tBody[0].row[nRow].style.backgroundColor = 'green';
   }
   for (var nRow = 0; nRow < tbl.tFoot[0].rows; nRow++)
   {
     tbl.tFoot[0].row[nRow].style.backgroundColor = 'yellow';
   }
}
</script>
</head>
<body onLoad='ColorBoxes()'>

<h1>The thead, tbody, and tfoot elements</h1>

<table id='MyTable'>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
    <tr>
      <th>Name</th>
      <th>Amount</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>$80</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Sum</td>
      <td>$180</td>
    </tr>
  </tfoot>
</table>

</body>
</html>

【问题讨论】:

  • .rows 属性是行的集合,而不是数字。

标签: javascript


【解决方案1】:

你可以做这样的事情。使用显式选择器可能会帮助您更好地推理循环。

function ColorBoxes() {
  const table = document.querySelector('#MyTable')
  const thead_tr = table.querySelectorAll('thead tr')
  const tbody_tr = table.querySelectorAll('tbody tr')
  const tfoot_tr = table.querySelectorAll('tfoot tr')

  thead_tr.forEach(row => {
    row.style.backgroundColor = 'red'
  })
  tbody_tr.forEach(row => {
    row.style.backgroundColor = 'green'
  })
  tfoot_tr.forEach(row => {
    row.style.backgroundColor = 'yellow'
  })
}
ColorBoxes()
<!DOCTYPE html>
<html>

<head>
  <style>
    table,
    th,
    td {
      border: 1px solid black;
    }
  </style>
</head>

<body>

  <h1>The thead, tbody, and tfoot elements</h1>

  <table id='MyTable'>
    <thead>
      <tr>
        <th>Month</th>
        <th>Savings</th>
      </tr>
      <tr>
        <th>Name</th>
        <th>Amount</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>January</td>
        <td>$100</td>
      </tr>
      <tr>
        <td>February</td>
        <td>$80</td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td>Sum</td>
        <td>$180</td>
      </tr>
    </tfoot>
  </table>

</body>

</html>

【讨论】:

    猜你喜欢
    • 2017-03-25
    • 2014-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多