[英]CSS nth-child selector not working for table created by JS
我有一個網頁,其中表格的內容來自 Google 表格。 我通過創建表格元素( tr
, td
)並將它們作為子元素添加到表格中,如下所示。 然后我嘗試應用 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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.