我目前正在处理一个项目,我必须填充表格的不同列,为此我正在使用.nextSibling
,但是如果我以第 4 列为目标,这些行可能会很长:
firstTd.nextSibling.nextSibling.nextSibling.nextSibling.innerHTML = "example";
所以我想知道是否有更优雅的方法,不需要每次都写.nextSibling
?
只要做一个小帮手:
const sibling = (el, count) => count ? sibling(el.nextSibling, count - 1) : el;
可用作
sibling(firstTd, 5).innerHTML = "example";
与其依赖这样的特定位置,这本质上是脆弱的(如果你添加一个新列怎么办?(,我建议给你的目标td
某种识别标记,比如类名或data-*
属性。然后,您将使用:
tr.querySelector(".the-class").innerHTML = "example";
如果你手边没有tr
,你可以从firstTd.parentNode
.
当然,因为querySelector
不仅关注孩子,而且关注所有后代,所以您需要为此做好计划。
现场示例:
// In a real situation I'd use a delegated handler, but the goal here is to
// show that the same code works regardless of the starting point
document.querySelectorAll("td:not(.x)").forEach(el => {
el.addEventListener("click", function() {
this.parentNode.querySelector(".ex").innerHTML = Math.random();
});
});
table {
border-collapse: collapse;
border: 1px solid #aaa;
}
td {
border: 1px solid #aaa;
padding: 4px;
}
<table>
<tbody>
<tr>
<td>Click me</td>
<td>Or me</td>
<td>Or me</td>
<td class="ex"></td>
</tr>
</tbody>
</table>
或者,给自己一个"查找我的下一个匹配兄弟姐妹"函数,该函数接受选择器:
const findNext = (el, selector) => {
let sib = el.nextElementSibling;
while (sib && !sib.matches(selector)) {
sib = sib.nextElementSibling;
}
return sib;
};
然后
findNext(firstTd, ".the-class").innerHTML = "example";
现场示例:
const findNext = (el, selector) => {
let sib = el.nextElementSibling;
while (sib && !sib.matches(selector)) {
sib = sib.nextElementSibling;
}
return sib;
};
// In a real situation I'd use a delegated handler, but the goal here is to
// show that the same code works regardless of the starting point
document.querySelectorAll("td:not(.x)").forEach(el => {
el.addEventListener("click", function() {
findNext(this, ".ex").innerHTML = Math.random();
});
});
table {
border-collapse: collapse;
border: 1px solid #aaa;
}
td {
border: 1px solid #aaa;
padding: 4px;
}
<table>
<tbody>
<tr>
<td>Click me</td>
<td>Or me</td>
<td>Or me</td>
<td class="ex"></td>
</tr>
</tbody>
</table>
可以通过索引访问表行和单元格:
table1.rows[2].cells[2].innerText = 42
<table id=table1>
<tr> <th> A </th> <th> B </th> <th> C </th> </tr>
<tr> <td> 1 </td> <td> 2 </td> <td> 3 </td> </tr>
<tr> <td> 4 </td> <td> 5 </td> <td> 6 </td> </tr>
</table>