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
How to create list in HTML dynamically?
提问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 a
is an Array of Objects for the list content, i
is the index variable passed to the callback function by jQuery.each
($.each
) and v
is the value for that index.
其中a
是列表内容的对象数组,i
是jQuery.each
( $.each
)传递给回调函数的索引变量,是该索引v
的值。
For reference: http://api.jquery.com/jQuery.each/.