Javascript jQuery:Order-Inside.contents()
如果我这样做:Javascript jQuery:Order-Inside.contents(),javascript,jquery,Javascript,Jquery,如果我这样做: function getAllTextNodes(root) { root = $(root || "body"); return root.find("*:not(iframe)").contents().filter(function() { return this.nodeType === 3 && //Node.TEXT_NODE = 3 $.trim(this.nodeValue) !== ""; }); } getAl
function getAllTextNodes(root) {
root = $(root || "body");
return root.find("*:not(iframe)").contents().filter(function() {
return this.nodeType === 3 && //Node.TEXT_NODE = 3
$.trim(this.nodeValue) !== "";
});
}
getAllTextNodes($.parseHTML("<div><div>a<div>sub</div>b</div></div>"))
函数getAllTextNodes(根){
root=$(root | |“body”);
返回root.find(“*:not(iframe)”).contents().filter(函数(){
返回this.nodeType===3&&//Node.TEXT\u Node=3
$.trim(this.nodeValue)!=“”;
});
}
getAllTextNodes($.parseHTML(“asubb”))
结果是一个带有“a”、“b”和“sub”的数组。因此,它们似乎遍历了结构,当它们到达一个元素时,它们会对该元素进行处理,然后继续嵌套元素
虽然这可能是有意义的(或者在某些情况下并不重要),但它会给我带来一些麻烦,因为我需要一种逻辑,可以按照元素在DOM树中出现的顺序返回元素,也就是说,我很乐意看到“a”、“sub”和“b”被返回
这是jQuery特意构建的吗?我能改变一下顺序吗?还是这是一只虫子
这是jQuery特意构建的吗?还是这是一只虫子
我不认为这是故意的,但考虑到选择器API甚至大多数修改方法的结果都是按DOM顺序排列的,这可能会被认为是一个bug。从您所展示的内容来看,contents
是通过一个简单的flatMap(el=>el.childNodes)
实现的
我能改变一下顺序吗
是的,您可以在jQuery对象上使用,该对象在内部使用:
return $.uniqueSort(root.find("*:not(iframe)").contents().filter(function() {
return this.nodeType === 3 && $.trim(this.nodeValue) !== "";
}));
然而,jQuery对于文本节点来说并不太好。在这里使用本机DOM API可能更简单,例如:
const it = document.createNodeIterator(root[0], NodeFilter.SHOW_TEXT, node => node.data.trim() != ""),
res = [];
for (let node; node = it.nextNode(); )
res.push(node);
return res;