我想知道属性https://www.w3schools.com/jsref/prop_node_nextsibling.asp在使用()方法时是如何工作的?下面是一个显示问题的代码示例:
function Sibling() {
var x = document.getElementsByClassName('firstClass')[0];
document.getElementById("out1").innerHTML = 'We are on <b> ' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
x = x.nextSibling;
document.getElementById("out2").innerHTML = 'After SINGLE nextSibling we are on <b> ' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>. WHY IS THAT???!!!';
x = x.nextSibling;
document.getElementById("out3").innerHTML = 'After DOUBLE nextSibling we are on <b> ' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';;
}<div class="general">
<div class="firstClass">
</div>
<div class="secondClass">
</div>
<button onclick="Sibling()">ClickMeAndThenExplainTheResults</button>
</div>
<p id="out1"></p>
<p id="out2"></p>
<p id="out3"></p>
因此,在完成第一个NextSibling之后,我希望得到第二个元素:
<div class="secondClass">,但出于众所周知的原因,需要调用double NextSibling才能从第一个元素转移到第二个元素。正如您所看到的,在第一个NextSibling之后,对象的TypeName是文本。但我没看到任何短信。
请您解释一下为什么我们需要使用两个NextSibling,以及在使用第一个NextSibling之后文本对象得到了什么
发布于 2018-05-11 12:17:10
nextSibling获取下一个节点,而不是一个元素的下一个节点。
在两个div元素节点之间,有一个包含空白的文本节点(空格、制表符和新行是文本),这就是您要得到的。
比较:
1: <div></div> <div></div>
2: <div></div><div></div>发布于 2018-05-11 12:27:55
当nextSibling返回下一个Node对象(甚至是空格或行提要)时,
您必须使用nextElementSibling代替。
有关详情,请参阅本问题:
Whats the difference between nextElementSibling vs nextSibling
下面是一个有用的片段:
(function Sibling() {
var x = document.getElementsByClassName('firstClass')[0];
document.getElementById("out1").innerHTML = 'Current: <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
x = x.nextElementSibling;
document.getElementById("out2").innerHTML = 'Next 1 : <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
x = x.nextElementSibling;
document.getElementById("out3").innerHTML = 'Next 2 : <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
})()<div class="general">
<div class="firstClass">
</div>
<div class="secondClass">
</div>
<button>I do nothing</button>
</div>
<p id="out1"></p>
<p id="out2"></p>
<p id="out3"></p>
希望能帮上忙。
https://stackoverflow.com/questions/50292161
复制相似问题