0

我遍历 jQuery 对象列表并检查 nextSibling 属性是否为null. 不幸的是,html 注释被视为对象类型的兄弟。我怎么能抓住这个?我需要一个触发的 if 语句obj.nextSibling == null || obj.nextSibling == comment

4

3 回答 3

2

如何编写一个函数来完成它,它只返回元素(即node.nodeType === 1

function nextElement(node) {
    while (node = node.nextSibling) if (node.nodeType === 1) return node;
    return null;
}

这是做什么的,

// while
node = node.nextSibling // get next sibling, if falsy break while
if (node.nodeType === 1) // if it is an Element, return it
// else go back to while
return null; // if we get here, next sibling was null

您可以在 MDN 上看到nodeType 不同值列表。

于 2013-06-14T14:33:44.833 回答
1

注释节点不是null,它们是注释节点(如果它们是,null它们会使第一个条件为真......)。因此,您需要测试它nodeType以查看它是否是评论。

obj.nextSibling == null || obj.nextSibling.nodeType == 8

参考:https ://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType

于 2013-06-14T14:49:30.343 回答
0

也许您需要使用.filter("*");过滤掉评论节点

像这样:

obj.siblings().filter("*")

obj.siblings("*")

于 2013-06-14T14:29:49.187 回答