Javascript 如何在 HTML 中动态创建列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5308125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:34:54  来源:igfitidea点击:

How to create list in HTML dynamically?

javascriptjqueryhtmljquery-mobile

提问by selladurai

In my jQuery mobile app, I want to display the result from a web service in a list. How do I create the list dynamically?

在我的 jQuery 移动应用程序中,我想在列表中显示来自 Web 服务的结果。如何动态创建列表?

回答by Erik Sandberg

var arr = ["list", "items", "here"];
$("div").append("<ul></ul>");
for(var i in arr) {
    var li = "<li>";
    $("ul").append(li.concat(arr[i]))
}

回答by FK82

Better yet,

更好的是,

$.each(
    a ,
    function(i,v) {
        $("#target_id").append("<li>" + v + "</li>") ;
    }
) ;

Where ais an Array of Objects for the list content, iis the index variable passed to the callback function by jQuery.each($.each) and vis the value for that index.

其中a是列表内容的对象数组,ijQuery.each( $.each)传递给回调函数的索引变量,是该索引v的值。



For reference: http://api.jquery.com/jQuery.each/.

供参考:http: //api.jquery.com/jQuery.each/