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"
}
]
}
]
}
哦,你是对的,非常感谢! –
嘿,没问题,祝你好运 –