从数组遍历循环创建li并显示为HTML列表 [英] Create li from loop through array and display to HTML as a list

查看:639
本文介绍了从数组遍历循环创建li并显示为HTML列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习javaScript,我想循环数组并显示为HTML作为列表.我该怎么办?

I am learning javaScript and I want to loop array and display to HTML as a list. How can I do that?

数组: var array = ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5', 'Slide 6', 'Slide 7', 'Slide 8', 'Slide 9'];

Array: 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>

推荐答案

尽管提供的所有答案都可以正常工作-它们都遇到相同的问题-因为每次迭代都将元素附加到DOM.如果列表很小,这将不是问题,但是,如果您要处理列表中所需的大量元素,则不断操作hte DOM会降低性能.

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.

更好的方法是(IMO)构建一个li的单个字符串,然后在完全迭代该数组时-通过一次操作在DOM中使用.innerHTML将字符串传递给UL.结果相同-但速度更快.

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.

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>

这篇关于从数组遍历循环创建li并显示为HTML列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆