2017-03-29 61 views
1

下面的作品,但它留下一些<li>進行轉換時,看到this jsFiddle輸出,我們將看到它留下一些節點出如何將所有嵌套列表節點轉換爲json?

HTML

<div id="tree"> 
    <ul class="sortable"> 
    <li>Pallacanestro 
     <ul class="sortable"> 
      <li>Dinamo 
       <ul class="sortable"> 
        <li>Logan</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
    <li>Calcio 
     <ul class="sortable"> 
      <li>Milan 
       <ul class="sortable"> 
        <li>Goal</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
    </ul> 
</div> 
<div id="d" style="margin-top: 40px; padding-top: 20px;">Output:<br><br><pre></pre></div><br><pre></pre></div> 

JS

var out = []; 
function processOneLi(node) {  
    var aNode = node.contents().first(); 
    var retVal = { 
     "name": aNode.text().trim(), 
     "url": aNode.attr("href") 
    }; 
    node.find("> .sortable > li").each(function() { 
     if (!retVal.hasOwnProperty("children")) { 
      retVal.children = []; 
     } 
     retVal.children.push(processOneLi($(this))); 
    }); 
    return retVal; 
} 
$("#tree > ul > li").each(function() { 
    out.push(processOneLi($(this))); 
}); 

$('#d pre').text(JSON.stringify(out[0], null, 2)); 

輸出缺少一個<li>

{ 
    "name": "Pallacanestro", 
    "children": [ 
    { 
     "name": "Dinamo", 
     "children": [ 
     { 
      "name": "Logan" 
     } 
     ] 
    } 
    ] 
} 

回答

1

如果我正確理解你,你說你在輸出中缺少Calcio。

你需要改變:

$('#d pre').text(JSON.stringify(out[0], null, 2));

$('#d pre').text(JSON.stringify(out, null, 2));

你只要求它輸出的第一個項目在數組中了。你想顯示整個數組。

+0

哦,你是對的,非常感謝! –

+1

嘿,沒問題,祝你好運 –