2017-03-29 56 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

嘿,没问题,祝你好运 –