mor*_*dev 13 javascript siblings
我希望以下代码能够"警告"
<input type=text onfocus="alert(this.nextSibling.id)" />
<output id="out">this is output</output>
Run Code Online (Sandbox Code Playgroud)
但它警告未定义为什么?
und*_*ned 13
nextSibling选择元素的下一个兄弟节点.下一个节点也可以是textNode没有id属性的节点,因此您可以获得该undefined值.作为其他的答案提示你可以使用nextElementSibling其是指具有一个兄弟节点属性nodeType的1(即Element对象)或取出元件之间的隐藏的字符.
请注意,IE8不支持该nextElementSibling属性.
试试这个:
alert(this.nextElementSibling.id);
Run Code Online (Sandbox Code Playgroud)
注意:
该nextSibling属性返回紧跟在指定节点之后的节点,在同一树级别中.
该nextElementSibling只读属性返回后立即指定一个在其父的孩子列表,或者为null如果指定的元素是最后一个在列表中的元素.
为什么你有这个问题
nextSibling选择元素的下一个同级节点。在您的情况下,您有一个文本节点作为下一个节点,因为元素节点之间有一个新行。元素节点之间的每个文本节点将被选为下一个节点,并且该节点没有属性id。
为了防止这种情况,我们可以使用两种方法:
解决方案一:
我们删除新行、所有空格、注释节点或其他文本节点,然后我们可以使用nextSibling:
<input type="button" value="get next sibling value" onclick="console.log(this.nextSibling.value)"><input type="text" value="txt 1">Run Code Online (Sandbox Code Playgroud)
解决方案2:
nextSibling我们使用以下属性来代替nextElementSibling:
<input type="button" value="get next sibling value" onclick="console.log(this.nextElementSibling.value)">
<input type="text" value="txt 1">Run Code Online (Sandbox Code Playgroud)
该nextElementSibling属性返回紧随其父项的子项列表中指定元素之后的元素,如果指定元素是列表中的最后一个元素,则返回 null。
如果像 IE8 这样的浏览器不支持该nextElementSibling属性,我们可以使用 polyfill(它应该放在代码之前):
if(!('nextElementSibling' in document.documentElement))
{
Object.defineProperty(Element.prototype, 'nextElementSibling',
{
get: function()
{
var e = this.nextSibling;
while (e && e.nodeType !== 1)
e = e.nextSibling;
return e;
}
});
}
Run Code Online (Sandbox Code Playgroud)
相关链接: