当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Add new list item dynamically to web page

问题描述:

Is there a way to add new list items in HTML automatically by getting the data of these list items from a web page.

The list is like this:

<ol class="treeBody">

<li>

<label for="folder1"><span id="albumname">0</span></label> <input type="checkbox" id="albumname" />

<ol>

<li>

<label for="subfolder1"><span id="subdirname">0</span></label> <input type="checkbox" id="subdirname" />

<ol>

<li class="file"><a href="">File 1</a></li>

</ol>

</li>

</ol>

</li>

</ol>

I get the data using websocket:

$.get("http://localhost:8040/api/album", function (data) {

console.log("data: ", data);

var i;

var j;

console.log(i);

for (i = 0; i < data.length; i++) {

console.log("start for loop");

var albname = data[i].Name;

console.log("albname: ", albname);

$("#albumname").text(albname);

var subalbum = data[i].SubAlbums

for (j = 0; j < subalbum.length; j++) {

var subname = data[i].SubAlbums[j];

console.log("SubName: ", subname);

$("#subdirname").text(subname);

}

}

});

网友答案:

Try this recursive function

function renderMenu(data){

    var menu = '<ul>';

    if(data.items.length){

        for(var i = 0; i < data.items.length; i++){
            var li = '<li>';

            if(data.items[i].link)
                li += '<a href="' + data.items[i].link + '">';

            if(data.items[i].title)
                li += data.items[i].title;

            if(data.items[i].link)
                li += '</a>';

            if(data.items[i].items) {
                var sub_menu = renderMenu(data.items[i]);
                li += sub_menu;
            }

            li += '</li>';

            menu += li;
        }
    }

    menu += '</ul>';

    return menu;
}

//structure JSON
var data = {
    'items': [
        {
            'link' : 'http://test.com',
            'title' : 'Root',
            'items' : [
                {
                    'link' : 'http://test.test.com',
                    'title' : 'sub-item',
                    'items' : [
                        {
                            'link' : 'http://test.test.test.com',
                            'title' : 'sub-sub-item'
                        }
                    ]
                }
            ]
        },
        {
            'link' : 'http://test.com/t1',
            'title' : 'Item-2'
        },
        {
            'link' : 'http://test.com/t1',
            'title' : 'Item-3'
        }
    ]
};

renderMenu(data);
分享给朋友:
您可能感兴趣的文章:
随机阅读: