jQuery 在 DIV 中创建无序列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/886570/
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-26 10:01:21  来源:igfitidea点击:

Creating unordered list in a DIV

jquery

提问by Musa

I have a DIV. I want to dynamically generate a bulleted list inside the DIV using jQuery with a items list I have with me

我有一个 DIV。我想使用 jQuery 在 DIV 内动态生成一个项目符号列表,其中包含我随身携带的项目列表

for (cnt = 0; cnt < someList.length; cnt++) {
  someList[cnt].FirstName + ":" + someList[cnt].LastName + "<br/>"
  // what to write here?
}

回答by Jose Basilio

Keeping things as simple as possible. Using your existing javascript, You would just need to add this:

使事情尽可能简单。使用您现有的 javascript,您只需要添加以下内容:

$('#myDiv').append("<ul id='newList'></ul>");
for (cnt = 0; cnt < someList.length; cnt++) {
  $("#newList").append("<li>"+someList[cnt].FirstName + ":" + someList[cnt].LastName+"</li>");
}

Since your HTML already has the DIV:

由于您的 HTML 已经具有 DIV:

<div id="myDiv"></div>

回答by kgiannakakis

Script:

脚本:

$(function(){
    someList = [ {FirstName: "Joe", LastName: "Smith"} ,
                 {FirstName: "Will", LastName: "Brown"} ]

    $("#target").append("<ul id='list'></ul>");
    $.each(someList, function(n, elem) {
       $("#list").append("<li>" + elem.FirstName + " : " + elem.LastName + "</li>");
    });
});

and html:

和 html:

<div id="target" />

回答by Luke Schafer

hacky

黑客

var list = "<ul>"
for (cnt = 0; cnt < someList.length; cnt++) {
    list += "<li>" + someList[cnt].FirstName + ":" + someList[cnt].LastName + "</li>"
}
list += "</ul>";

no even bothering with creating dom objects properly :)

甚至不用费心正确创建 dom 对象:)