我正在尝试在Javascript中创建一个递归函数,它应该基本上给我像BELOW
这样的HTML <li><a class="expand">+</a> <span class="treeNodeInner"><a id="7471">Ringtones</a>
<ul>
<li><span class="treeNodeInner"><a id="7995">Top Tones</a></span></li>
<li><span class="treeNodeInner"><a id="8642">Country</a></span></li>
<li><span class="treeNodeInner"><a id="8640">Rock</a></span></li>
</ul>
</span></li>
我使用以下函数使用javascript制作上述html。 它基本上是一个树视图,我们将有节点和子节点的东西。
我正在努力通过以下功能实现上述HTML结构,请使用以下功能建议修改
function GenerateNodes(categItem) {
var parentNode = "<li>"; //parent li
if (categItem.SubCategory != null && categItem.SubCategory != undefined && categItem.SubCategory.Count > 0) {
parentNode = "<li><a class='expand'>+</a>";
}
parentNode += "<input type='radio' name='category' /><span class='treeNodeInner'><a id='" + categItem.ID + "'>" + categItem.name + "</a> "; //need to close the span
if (categItem.SubCategory != null && categItem.SubCategory != undefined && categItem.SubCategory.Count > 0) {
var subNode = "<span><ul>";
for (var index = 0; index < categItem.SubCategory.Count; index++) {
subNode += GenerateNodes(categItem.SubCategory[index]);
subNode += "</ul></span>"
}
parentNode += subNode
}
parentNode += "</span></li>"
}
由于
答案 0 :(得分:1)
只需查看代码,我发现您没有在html中插入新的li
。我不确定你是否在代码的某个地方管理它。我复制了你的代码并对其进行了一些调试。然后我尝试使用一些代码在html上添加li
。请参阅以下代码:
//Insert this after parentNode += "</span></li>";
var newDiv = document.createElement('div');
newDiv.innerHTML = parentNode;
categItem.appendChild(newDiv.childNodes[0]);
//I assume that categItem is the id of the container as your sample html code
//above is not clear to me. So I did using sample html below
<div id="liContainer">
</div>
请参阅此jsfiddle上述代码的工作原理。我知道这不是你想要的,但我希望你能从中得到一些想法。