如何将JavaScript对象数组数据渲染到HTML DOM并生成展示列表
问题原因
- HTML中仅存在1个类为
targets的<li>元素,遍历数组时每次直接覆盖该元素的innerHTML,最终只会显示数组最后一条数据 - 循环逻辑颠倒:外层遍历数组项、内层遍历列表元素的写法,会导致每轮数组遍历都全量覆盖所有列表元素的内容,无法实现多条数据对应多个列表项的需求
修复方案
方案1:动态生成列表项(性能最优)
先给列表容器加唯一标识,方便选中操作:
<ul id="eventList"></ul>
修改JS代码,先拼接所有列表项内容再一次性插入DOM:
const allData = [{ date: '2nd', venue: 'venue1', location: 'location1', }, { date: '3rd', venue: 'venue2', location: 'location2', }, { date: '4th', venue: 'venue3', location: 'location3', } ] const eventList = document.querySelector('#eventList') let listHtml = '' allData.forEach(data => { listHtml += ` <li class="targets"> <h5>DATE</h5> <h4>${data.date}</h4> <h5>VENUE</h5> <h4>${data.venue}</h4> <h5>LOCATION</h5> <h4>${data.location}</h4> <button>BUY TICKETS</button> </li> ` }) eventList.innerHTML = listHtml
方案2:基于原有模板节点克隆生成
如果需要保留原有单个<li>作为模板的写法,可以用节点克隆的方式实现:
<ul> <li class="targets"></li> </ul>
const allData = [{ date: '2nd', venue: 'venue1', location: 'location1', }, { date: '3rd', venue: 'venue2', location: 'location2', }, { date: '4th', venue: 'venue3', location: 'location3', } ] const listContainer = document.querySelector('ul') const targetTemplate = document.querySelector('.targets') // 先移除原模板节点 targetTemplate.remove() allData.forEach(data => { const newItem = targetTemplate.cloneNode(true) newItem.innerHTML = ` <h5>DATE</h5> <h4>${data.date}</h4> <h5>VENUE</h5> <h4>${data.venue}</h4> <h5>LOCATION</h5> <h4>${data.location}</h4> <button>BUY TICKETS</button> ` listContainer.appendChild(newItem) })
内容的提问来源于stack exchange,提问作者user3718511
相关产品推荐
相关产品推荐

