How can I dynamically create an unordered list in JavaScript?
I have a global JavaScript array that contains some strings.
I want to create a dynamic list based on the strings in my JavaScript array. Similar to this:
<ul class='xbreadcrumbs' style='position:absolute; bottom:0px'>
<li>
<a href='#'>String 1</a>
</li>
</ul>
How can I iterate over m开发者_StackOverflowy array, and then create this list in JavaScript/jQuery?
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:
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.
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);
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!
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):
var ul = "<ul>";
for(var i=0; i < arr.length; i++) {
ul += "<li><a href=\"#\">" + arr[i] + "</a></li>";
}
ul += "</ul>";
var ulElem = $(ul);
精彩评论