使用 JavaScript 递归函数创建 HTML 不起作用



我正在尝试在Javascript中创建一个递归函数,它基本上应该给我像下面这样的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>"
}

谢谢

只需查看代码,我发现您没有在 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 上面的代码是如何工作的。我知道这不是你想要的,但我希望你能从中得到一些想法。

最新更新