在这个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
标签。
答案 0 :(得分:2)
t2
是指td#t2
,因为ID为&#34; t2&#34;是td
元素本身。
t2.firstChild
指的是t2
内的文本节点,它是唯一的子节点。独生子女没有兄弟姐妹。
您可能想要查看t2
本身:
var t2 = document.getElementById("t2");
console.log(t2.nextElementSibling);
console.log(t2.nextSibling);