将HTML div内容转换为json对象

时间:2012-11-22 19:28:37

标签: javascript jquery html json

我目前有以下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,但嵌套使事情变得复杂。

请帮帮忙?

提前致谢。

1 个答案:

答案 0 :(得分:2)

执行此操作的最简单方法是使用递归函数,该函数接收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;
}