4

我目前有以下 HTML ...

<div id="tabs-1" class="tabs-1 ui-tabs-panel ui-widget-content ui-corner-bottom ui-droppable" aria-labelledby="layoutName" role="tabpanel" aria-expanded="true" aria-hidden="false" style="z-index: auto;">

    <div id="mosami1" class="mosami ui-draggable ui-draggable-dragging inside-drop-zone highlight "  style="position: absolute; left: 38.4735%; top: 78.1949%; width: 19.3344%; z-index: 100;">
        <div class="ui-resizable-handle ui-resizable-n" style="z-index: auto; margin-left: 119.583px;"></div>
        <div class="ui-resizable-handle ui-resizable-s" style="z-index: auto; margin-left: 119.583px;"></div>
        <div class="ui-resizable-handle ui-resizable-ne" style="z-index: auto;"></div>
        <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: auto;"></div>
        <div class="ui-resizable-handle ui-resizable-nw" style="z-index: auto;"></div>
        <div class="ui-resizable-handle ui-resizable-sw" style="z-index: auto;"></div>
    </div>
</div>

...我想变成 JSON 如下:

{
    "divID": {
        "options": {
            "id": "tabs-1",
            "class": "tabs-1 ui-tabs-panel ....",
            "z-index": "auto",
        }
        "div": {
            "options": {
                "id":"mosami1",
                "class": "mosami ui-draggable ui-draggable-dragging"
                "z-index": "100",
                "left": "38.47"
            },
        },
        "div1": {
            "class": "ui-resizable-handle ui-resizable-n"
            "z-index": "auto"
        }
    }
    //...
} 

我正在尝试使用 JQuery 来做到这一点,但是嵌套使事情变得复杂。

请帮忙?

提前致谢。

4

1 回答 1

3

最简单的方法是使用一个递归函数,该函数接受一个 jQuery 节点并返回一个表示该节点数据的 javascript 对象。解析传入节点的选项,然后遍历调用递归函数的 jQuery 节点的子节点。像这样的东西:

var parse = function($el) {
  var result = {};

  result.options = {
    // parse $el for properties
  };

  $el.children().each(function(i, e) {
    result[$(this).prop('tagName') + i] = parse($(this));
  })

  return result;
}
于 2012-12-03T02:04:09.193 回答