繁体   English   中英

使用javascript递归函数创建HTML无效

[英]create HTML using javascript recursive function not working

我正在尝试用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 ,上面的代码如何工作。 我知道这并不是您想要的,但我希望您能从中得到一些想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM