替代.nextSibling?

时间:2018-06-02 13:57:04

标签: javascript

我目前正在处理一个项目,我必须填写表格的不同列,因为我使用.nextSibling,但如果我定位,那么这些行可能很长,让& #39; s说第4栏:

firstTd.nextSibling.nextSibling.nextSibling.nextSibling.innerHTML = "example";

所以我想知道是否有更优雅的方式,每次都不需要写.nextSibling

3 个答案:

答案 0 :(得分:3)

只需做一个小帮手:

 const sibling = (el, count) => count ? sibling(el.nextSibling, count - 1) : el;

可以用作

sibling(firstTd, 5).innerHTML = "example";

答案 1 :(得分:3)

而不是依赖于这样一个特定的位置,这本身就很脆弱(如果添加一个新列怎么办?),我建议给你的目标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>

答案 2 :(得分:1)

index可以访问表行和单元格:

&#13;
&#13;
table1.rows[2].cells[2].innerText = 42
&#13;
<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>
&#13;
&#13;
&#13;