繁体   English   中英

jQuery-解析DOM并创建树结构(复合模式)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM