开发者

create HTML using javascript recursive function not working

I am trying to make a recursive function in Javascript which should basically give me HTML like BELOW

 <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>

I am using the below function to make the above html using javascript. Its basically a tree view were we will have nodes and sub nodes kind of thing.

I am struggling the achieve the above HTML structure through below function, please advise modifications with the below function

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>"
}

Thanks


Simply looking at the code, I found out that you are not inserting the new li in your html. I'm not sure if you manage this somewhere out of your code. I'd copied your code and do some debug on it. Then I try to add the li on the html using some code. See code below:

//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>    

See this jsfiddle how the above code work. I know this is not exactly what you want, but I hope you can get some idea from this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜