【问题标题】:How does NextSibling work?NextSibling 是如何工作的?
【发布时间】:2018-10-21 20:40:29
【问题描述】:

我想知道属性 NextSibling 在使用方法 getElementsByClassName() 的情况下如何工作? 这是一个显示问题的代码示例:

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 之后看到的,对象的 TypeNameText。但实际上我没有看到任何文字...

您能否解释一下为什么我们需要使用两个 NextSibling 以及在使用第一个 NextSibling 之后 Text 对象会得到什么?

【问题讨论】:

    标签: javascript html dom


    【解决方案1】:

    由于nextSibling 返回下一个 Node 对象(甚至是空格或换行符),
    您必须要改用nextElementSibling

    详情请看这个问题:
    Whats the difference between nextElementSibling vs nextSibling

    这是一个有效的 sn-p:

    (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>

    希望对你有帮助。

    【讨论】:

    • 也谢谢。 nextElementSibling 在我的情况下更有用。
    【解决方案2】:

    nextSibling 获取下一个节点,而不是作为元素的下一个节点

    在两个 div 元素节点之间,有一个包含空格的文本节点(空格、制表符和换行符文本),这就是你得到的。

    比较:

    1: <div></div> <div></div>
    2: <div></div><div></div>
    

    另见nextElementSibling

    【讨论】:

    • 该死!很简单!谢谢! :D
    猜你喜欢
    • 2011-10-27
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 2017-07-24
    相关资源
    最近更新 更多