我目前正在进行一个项目,我必须填充表的不同列,因为我使用的是.nextSibling,但是如果我的目标是第4列,则行可能很长:
firstTd.nextSibling.nextSibling.nextSibling.nextSibling.innerHTML = "example";所以,我想知道是否有更优雅的方法可以做到这一点,而不是每次都需要编写.nextSibling?
发布于 2018-06-02 13:59:25
只要做个小帮手:
const sibling = (el, count) => count ? sibling(el.nextSibling, count - 1) : el;它可以用作
sibling(firstTd, 5).innerHTML = "example";发布于 2018-06-02 14:06:06
与其依赖这样的特定位置(这种位置本质上是脆弱的(如果您添加了一个新列怎么办?),我建议给目标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>
发布于 2018-06-02 14:14:27
索引可以访问表行和单元格
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>
https://stackoverflow.com/questions/50657650
复制相似问题