【问题标题】:CSS nth-child selector not working for table created by JSCSS nth-child 选择器不适用于 JS 创建的表
【发布时间】:2020-05-05 18:04:55
【问题描述】:

我有一个网页,其中表格的内容来自 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() 添加每个元素时,兄弟部分没有更新是不是原因?到底发生了什么?

【问题讨论】:

  • querySelector 只返回第一个匹配项。你可能需要querySelectorAll
  • 另外:一个给定的元素只能在 DOM 中的一个位置。当您执行 .map() 操作时,您会一遍又一遍地附加相同的 &lt;tr&gt; 元素,这将不起作用。
  • @volt,你说得对,我完全忘记了。如果您回答,我将其标记为答案。
  • @Pointy,对。感谢您指出了这一点。我将tbBody.appendChild(tr); 放在第二个.map() 之后

标签: javascript html css html-table css-selectors


【解决方案1】:

您应该使用 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";
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多