2012-11-22 108 views
3

目前,我有以下的HTML ...轉換HTML DIV內容JSON對象

<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來做到這一點,但嵌套使事情變得複雜。

請幫忙?

在此先感謝。

回答

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; 
}