javascript - CSS nth-child 选择器不适用于 JS 创建的表

标签 javascript html css html-table css-selectors

我有一个网页,其中表格的内容来自 Google 表格。我通过创建表元素(trtd)并将它们作为子元素附加到表中,如下所示。然后我尝试应用 CSS 用不同的颜色为交替行着色。事实证明,它只对所选内容的第一个实例进行着色。

HTML

<table id="list">
 <thead></thead>
 <tbody></tbody>
</table>

JS

document.addEventListener('DOMContentLoaded', function() {
  google.script.run.withSuccessHandler(makeList).getList();
});

// my Google Sheet data is in the "data" parameter below
function makeList(data) {
  console.log(data[0]);

  // Add Header
  var tbHead = document.querySelector('#list thead');
  var tr = document.createElement('tr');

  data[0].map(function(h) {
    var th = document.createElement('th');
    th.textContent = h;
    tr.appendChild(th);
    tbHead.appendChild(tr);
  });

  data.splice(0,1);
  console.log(data[0]);

  // Add rows
  var tbBody = document.querySelector('#list tbody');

  data.map(function(r) {
    var tr = document.createElement('tr');
    r.map(function(d) {
      var td = document.createElement('td');
      td.textContent = d;
      tr.appendChild(td);
      tbBody.appendChild(tr);
    });
  });

  // At this point the table is filled correcty (at leat visually)

  // Styling table
  configureTable();
}

// JS to change CSS of Table
function configureTable() {

  // The selection below selects only the second element of the table body, and not all of the even elements, the same happens if I select 2n.
  var tbEvenRow = document.querySelector("#list tbody tr:nth-child(even)");
  tbEvenRow.style.backgroundColor = "cyan";
}

那么,这是否是当我使用 appendChild() 添加每个元素时同级部分未更新的原因?到底发生了什么?

最佳答案

您应该执行 querySelectorAll 而不是 querySelector。因为 querySelector 只提供一个元素。所以你的代码将如下所示:

// JS to change CSS of Table
function configureTable() {

  // The selection below selects only the second element of the table body, and not all of the even elements, the same happens if I select 2n.
  var tbEvenRows = document.querySelectorAll("#list tbody tr:nth-child(even)");
  for ( let i = 0; i < tbEvenRows.length; i++) {

   tbEvenRoww[i].style.backgroundColor = "cyan";
  }
}

关于javascript - CSS nth-child 选择器不适用于 JS 创建的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59811272/

相关文章:

javascript - Heap 算法演练

javascript - replaceState() 与 pushState()

html - 我可以在 Rails 中使用哪些工具/方法从外部 URL 获取信息?

css - 在宽度变化时重新定位 DIV 菜单项

html - 电子邮件中的表格未在 MS Outlook 中居中

javascript - Yii2 从 js 脚本在页面上的 vendor 文件夹中添加图像、css、js 文件

javascript - 修改多维数组的一个索引会导致其他所有子数组发生变异?

javascript - 我怎样才能点击()这个图像?

javascript - 如何更新 Div 中的文本?

jquery - 如何查看使用模板生成的 jquerymobile 源代码?