Javascript 从循环遍历数组创建 li 并作为列表显示到 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46141450/
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
Create li from loop through array and display to HTML as a list
提问by gavgrif
I am learning javaScript and I want to loop array and display to HTML as a list. How can I do that?
我正在学习 javaScript,我想循环数组并作为列表显示到 HTML。我怎样才能做到这一点?
Array:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];
大批:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];
javascript:
javascript:
function listItem(item){
for (var i = 0; i < item.array.length; i++){
var list = item.array[i];
list = document.createElement('li');
document.getElementByClass('box').appendChild(list);
console.log(list);
}
}
<div class ="box"><ul></ul></div>
回答by gavgrif
Whilst all the supplied answers work and are fine - they all suffer from the same issue - in that they append the element to the DOM with each iteration. With a small list this will not be an issue, but if you are dealing with a large number of elements that you want in your list - the constant manipulation of hte DOM will have a performance cost.
虽然所有提供的答案都有效并且很好 - 它们都遇到相同的问题 - 因为它们在每次迭代时将元素附加到 DOM。对于一个小列表,这将不是问题,但是如果您要处理列表中所需的大量元素 - 对 DOM 的不断操作将带来性能成本。
It is far better (IMO) to build a single string of the li's and then when the array is fully iterated through - pass the string to the UL using .innerHTML - in the DOM in a single action. Same result - but faster.
最好 (IMO) 构建 li 的单个字符串,然后当数组完全迭代时 - 使用 .innerHTML 将字符串传递给 UL - 在单个操作中的 DOM 中。相同的结果 - 但更快。
var slides = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"]
var str = '<ul>'
slides.forEach(function(slide) {
str += '<li>'+ slide + '</li>';
});
str += '</ul>';
document.getElementById("slideContainer").innerHTML = str;
<div id="slideContainer"></div>
回答by stybl
Fairly simple:
相当简单:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"]
array.forEach(function(item) {
var li = document.createElement("li");
var text = document.createTextNode(item);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
});
<ul id="myUl"></ul>
This code does the following:
此代码执行以下操作:
- For each item of the array:
- Create a new
<li> - Create a text node with the text from the array
- Append the text to the
<li> - Append the
<li>to the<ul>
- Create a new
- 对于数组的每个项目:
- 创建一个新的
<li> - 使用数组中的文本创建文本节点
- 将文本附加到
<li> - 附加
<li>到<ul>
- 创建一个新的
This all becomes much simpler if you use jQuery:
如果您使用 jQuery,这一切都会变得更简单:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"];
array.forEach(function(item) {
$("#myUL").append("<li>" + item + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUL">
</ul>
EDIT:If you want to use a normal for loop instead of forEach, you can do like so:
编辑:如果你想使用普通的 for 循环而不是 forEach,你可以这样做:
var array = ["slide 1", "slide 2", "slide 3", "slide 4", "slide 5"];
for (i = 0; i < array.length; i++) {
var li = document.createElement("li");
var text = document.createTextNode(array[i]);
li.appendChild(text);
document.getElementById("myUl").appendChild(li);
}
<ul id="myUl"></ul>
The only difference in this code is that instead of using the built-in forEach method to loop through the array and perform operations on each element, we instead manually loop through the indices of the array.
这段代码的唯一区别是,我们没有使用内置的 forEach 方法循环遍历数组并对每个元素执行操作,而是手动循环遍历数组的索引。
回答by Thijs
You could use the ES6 method reduce and template literals. You could use them like this:
您可以使用 ES6 方法 reduce 和模板文字。你可以像这样使用它们:
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'],
// Reduce will iterate over all the array items and returns a single value.
listItems = array.reduce((result, item) => {
// Add a string to the result for the current item. This syntax is using template literals.
result += `<li>${item}</li>`;
// Always return the result in the reduce callback, it will be the value or result in the next iteration.
return result;
}, ''); // The '' is an empty string, it is the initial value result.
// Get the element from the DOM in which to display the list, this should be an ul or ol element.
resultElement = document.getElementById('result');
// Set the inner HTML
resultElement.innerHTML = listItems;
<ul id="result"></ul>
For more information on reduce see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce. And if you want to know more about template literals check here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
有关 reduce 的更多信息,请参见此处:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce。如果您想了解更多关于模板文字的信息,请点击此处:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
回答by Ori Drori
Convert the array into a string by using Array#joinand using list item tags as separators. Add the start and end tag manually using string concatenation (+). Assign the string to the list element (ul#target) using Element#innerHTML:
通过使用Array#join并使用列表项标签作为分隔符将数组转换为字符串。使用字符串连接 ( +)手动添加开始和结束标记。ul#target使用Element#innerHTML将字符串分配给列表元素 ( ) :
var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];
target.innerHTML = '<li>' + array.join('</li><li>') + '</li>';
<ul id="target"></ul>
回答by sg28
Try this ,also you can add to the list
试试这个,你也可以添加到列表中
var arr = [
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2),
Math.random().toFixed(2)
];
console.log(arr);
var ul = document.createElement('ul');
ul.className = 'myUL';
document.getElementById('container').appendChild(ul);
function myFunction() {
// for(var i =0;i<5;i++){
// arr.push(Math.random().toFixed(2));
// }
create(arr);
}
function create(arr){
arr.forEach(function(data){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += data;
li.className = "myList";
});
}create(arr);
#container .myUL{
padding:0px;
}
#container .myUL .myList {
list-style-type: none;
border:1px solid grey;
padding:5%;
border-radius:5px;
margin:4px;
}
.click{
width:80px;
height:30px;
border-radius:5px;
color:#fff;
background:#323232;
font-size:15px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<!-- create a ul li using js -->
<button class="click" onclick="myFunction()">Click Me</button>
<div id="container"></div>
</body>
</html>

