Javascript jQuery-解析DOM并创建树结构(复合模式)
我正在解析DOM,我想将匹配某个选择器的所有元素的层次结构提取到JavaScript对象树结构中,比如Javascript jQuery-解析DOM并创建树结构(复合模式),javascript,jquery,composite,Javascript,Jquery,Composite,我正在解析DOM,我想将匹配某个选择器的所有元素的层次结构提取到JavaScript对象树结构中,比如$(“[data node]”)。我没有找到一种标准的jQuery方法来实现这一点。使用jQuery.find()似乎会返回一个简单的列表。也许我错过了一些显而易见的事情 例如,我想分析以下内容: <div data-node="root"> <div class="insignificant-presentation"> <div>
$(“[data node]”)
。我没有找到一种标准的jQuery方法来实现这一点。使用jQuery.find()似乎会返回一个简单的列表。也许我错过了一些显而易见的事情
例如,我想分析以下内容:
<div data-node="root">
<div class="insignificant-presentation">
<div>
<div data-node="interestingItem">
</div>
</div>
<div>
<div data-node="anotherInterestingItem">
<div data-node="usefulItem">
</div>
</div>
</div>
不知道你为什么需要这个,但像这样的东西应该可以
$.fn.tree = function() {
var arr = [],
self = this;
(function runForrestRun(el, arr) {
var isEl = self.is(el),
children = [];
if (isEl)
arr.push({
"node" : el.data('node'),
"children": children
});
el.children().each(function() {
runForrestRun($(this), isEl ? children : arr);
});
}(this.first(), arr));
return arr;
}
函数createTree(根){
var children=[];
root.find('div[数据节点])。每个(函数(){
//我想不出更好的办法来不让同一个元素匹配两次。
if(!$(this).data('taged')){
$(this).data('taged',true);
push(createTree($(this));
}
});
返回{
“节点”:根数据(“节点”),
“儿童”:儿童
};
}
var tree=createTree($('div[data node]')。first();
document.write(“”+JSON.stringify([tree],0,2))
我理解为什么需要这样做的困惑。我有一个非常复杂的项目,我无法控制正在解析的标记。你的答案非常完美,令人印象深刻。这个答案对我一直很有用(不仅仅是在jQuery中),这个算法有一个通用的名字吗?这是一个很好的答案,几乎和比你早一点回答并解决问题的人一样,但我想我更喜欢他使用$.fn和self.is。@IanL,我同意adeneo解决方案是更好的选择。它们非常相似,因为递归编写函数的方法只有这么多。
$.fn.tree = function() {
var arr = [],
self = this;
(function runForrestRun(el, arr) {
var isEl = self.is(el),
children = [];
if (isEl)
arr.push({
"node" : el.data('node'),
"children": children
});
el.children().each(function() {
runForrestRun($(this), isEl ? children : arr);
});
}(this.first(), arr));
return arr;
}