我希望下面的代码能提醒"out“
<input type=text onfocus="alert(this.nextSibling.id)" />
<output id="out">this is output</output>但它会提醒不明原因?
发布于 2014-11-15 12:20:16
nextSibling选择元素的下一个同级节点。下一个节点也可以是没有textNode属性的id,因此可以得到undefined值。另一个答案表明,您可以使用nextElementSibling属性,它引用具有nodeType of 1 (即元素对象)的下一个兄弟节点,或者删除元素之间的隐藏字符。
注意,IE8不支持nextElementSibling属性。
发布于 2014-11-15 11:46:02
试试这个:
alert(this.nextElementSibling.id);注意:-- nextSibling属性在同一树级别上,在指定节点之后立即返回节点。
nextElementSibling只读属性将在其父元素的子列表中紧接指定元素之后返回元素,如果指定的元素是列表中的最后一个元素,则返回null。
发布于 2018-06-29 19:35:08
为什么你有这个问题
nextSibling选择元素的下一个同级节点。在您的示例中,您有一个文本节点作为下一个节点,因为元素节点之间有一条新的行。元素节点之间的每个文本节点将被选择为下一个节点,并且此节点不具有id属性。
为了防止这种情况,我们可以使用两种方法:
解决方案1:
我们删除新行、所有空白空间、注释节点或其他文本节点,然后可以使用nextSibling:
<input type="button" value="get next sibling value" onclick="console.log(this.nextSibling.value)"><input type="text" value="txt 1">
解决方案2:
我们使用的不是nextSibling,而是nextElementSibling属性:
<input type="button" value="get next sibling value" onclick="console.log(this.nextElementSibling.value)">
<input type="text" value="txt 1">
nextElementSibling属性将在其父元素的子列表中紧接指定元素之后返回元素,如果指定的元素是列表中的最后一个元素,则返回null。
在这种情况下,如果像IE8这样的浏览器不支持nextElementSibling属性,我们可以使用一个填充(它应该放在代码之前):
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;
}
});
}相关链接:
https://stackoverflow.com/questions/26945438
复制相似问题