我正在尝试在javascript中创建一个带有递归函数的html列表,但我真的不明白为什么实际结果与我的预期结果不符。
json
{
"sections": {
"1": {
"name": "Section 1",
"sections": {
"3": {
"name": "Section 1.1",
"sections": {
"4": {
"name": "Section 1.1.1",
"sections": {}
}
}
}
}
},
"2": {
"name": "Section 2",
"sections": {}
}
}
}
Javascript
$(document).ready(function() {
generateHtml(myLoadedJson);
});
function generateHtml(pData) {
var self = this;
var html = '';
if("sections" in pData) {
html+= '<ul>';
var objList = Object.keys(pData.sections);
var nbr = objList.length;
for(i=0; i<nbr; i++) {
var key = objList[i];
var obj = pData.sections[key];
html+= '<li><div>' + obj.name + '</div>'
html+= generateHtml(pData.sections[key]);
html+= '</li>';
}
html+= '</ul>';
}
return html;
};
预期结果
<ul>
<li>
<div>Section 1</div>
<ul>
<li>
<div>Section 1.1<div>
<ul>
<li>
<div>Section 1.1.1<div>
</li>
</ul>
</li>
</ul>
</li>
<li>
<div>Section 2</div>
</li>
</ul>
实际结果
<ul>
<li>
<div>Section 1</div>
<ul>
<li>
<div>Section 1.1</div>
<ul>
<li>
<div>section 1.1.1</div>
<ul></ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
有人有想法吗?