[英]jQuery - Parse DOM and create a tree structure (composite pattern)
我正在解析DOM,我想將與某個選擇器匹配的所有元素的層次結構提取為JavaScript對象樹結構,比如說$('[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>
並在JavaScript中創建如下結構:
[
{
"node": "root",
"children": [
{
"node": "interestingItem",
"children": []
},
{
"node": "anotherInterestingItem",
"children": [
{
"node": "usefulItem",
"children": []
}
]
}
]
}
]
不知道為什么需要這個,但是應該這樣做
$.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;
}
function createTree(root) { var children = []; root.find('div[data-node]').each(function() { // I can't think of a better way to not match the same ellement twice. if (!$(this).data('tagged')) { $(this).data('tagged', true); children.push(createTree($(this))); } }); return { "node": root.data('node'), "children": children }; } var tree = createTree($('div[data-node]').first()); document.write('<pre>' + JSON.stringify([tree], 0, 2))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <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> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.