在此 HTML 结构中:
<table id="outside">
<tr>
<td id="t1">one</td>
<td>a</td>
</tr>
<tr>
<td id="t2">two</td>
<td>b</td>
</tr>
</table>
为什么下面的脚本会这样:
// Function to change the content of t2
function modifyText() {
var t2 = document.getElementById("t2");
console.dir(t2.firstChild.nextElementSibling);
console.dir(t2.firstChild.nextSibling);
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
为什么 nextElementSibling
和 nextSibling
具有空值。我希望它们是兄弟 td
标签。
最佳答案
t2
引用 td#t2
,因为 ID 为“t2”的元素是 td
元素本身。
t2.firstChild
指的是 t2
内的文本节点,它是其唯一的子节点。独生子女没有 sibling 。
您可能想看看 t2
本身:
var t2 = document.getElementById("t2");
console.log(t2.nextElementSibling);
console.log(t2.nextSibling);
关于javascript - 当兄弟存在时,为什么 nextElementSibling 和 nextSibling 为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188262/