如何在 JavaScript 中动态创建无序列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7677028/
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 can I dynamically create an unordered list in JavaScript?
提问by Sheehan Alam
I have a global JavaScript array that contains some strings.
我有一个包含一些字符串的全局 JavaScript 数组。
I want to create a dynamic list based on the strings in my JavaScript array. Similar to this:
我想根据 JavaScript 数组中的字符串创建一个动态列表。与此类似:
<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>
<li>
<a href='#'>String 1</a>
</li>
</ul>
How can I iterate over my array, and then create this list in JavaScript/jQuery?
如何迭代我的数组,然后在 JavaScript/jQuery 中创建这个列表?
采纳答案by Vikas Naranje
Try this
尝试这个
var str = '<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>';
for(var i in $yourArray){
str += '<li><a href="#">String 1</a></li>';
}
str += '</ul>';
$('body').append(str);
回答by Jon Newmuis
If you only need a flat array (i.e. not multi-dimensional and no arrays within the array), then you can do the following in plain JavaScript:
如果您只需要一个平面数组(即不是多维数组且数组中没有数组),那么您可以在纯 JavaScript 中执行以下操作:
var strs = [ "String 1", "String 2", "String 3" ];
var list = document.createElement("ul");
for (var i in strs) {
var anchor = document.createElement("a");
anchor.href = "#";
anchor.innerText = strs[i];
var elem = document.createElement("li");
elem.appendChild(anchor);
list.appendChild(elem);
}
Then append list
to whichever parent element in the body you desire.
然后附加list
到您想要的正文中的任何父元素。
回答by jimbo
var $bread = $('ul.xbreadcrumbs');
$.each(yourArray, function(index, value) {
$('<li><a href="#">' + value + '</a></li>')
.appendTo($bread);
});
I have not tested this - just off my head. Hope this helps!
我还没有测试过这个 - 只是我的头脑。希望这可以帮助!
回答by John Keyes
Yes you can. You can either user the DOM directly with createElement
(see Jonathan's answer), or go an very easy route with jQuery (not tested):
是的你可以。您可以直接使用 DOM createElement
(请参阅 Jonathan 的回答),或者使用 jQuery(未测试)走一条非常简单的路线:
var ul = "<ul>";
for(var i=0; i < arr.length; i++) {
ul += "<li><a href=\"#\">" + arr[i] + "</a></li>";
}
ul += "</ul>";
var ulElem = $(ul);