如何在JavaScript中实现这个?
function prevAll (element) {
// some code to take all siblings before element?
return elements;
};
function prevAll (element) {
// some code to take all siblings before element?
return elements;
};
.previousElementSibling
,你可以获取前一个节点,该节点是实际元素 (不是文本节点或注释)。function prevAll(element) {
var result = [];
while (element = element.previousElementSibling)
result.push(element);
return result;
}
.previousElementSibling
属性如有需要,可以在IE8中进行polyfill。.reverse()
即可。previousSibling
属性,并循环直到其为null。const sibGen = function* (element) {
let sibling = element.previousElementSibling;
while(sibling !== null) {
sibling = sibling.previousElementSibling;
yield sibling
}
}
然后将其调用:
const siblingGenerator = sibGen(myElement);
// filter(Boolean) removes the null element
const allSiblings = [...siblingGenerator].filter(Boolean);
element
)。当你尝试了一些东西后回来..哦等等,我想SLaks想为你做所有的工作。等待他的编辑,然后你就可以毫不费力地离开了。 - musefan