如何用Vanilla JS从对象数组生成指定格式的无序列表?
使用Vanilla JS从对象数组生成指定格式的无序列表
你只需要在创建<li>元素后,为其填充包含加粗作者名和书名的内容即可,同时可以优化DOM操作的效率(避免重复查询myUL元素)。以下是完整实现代码:
HTML
<div id="myDiv"></div>
JavaScript
let myObj = [ {name: "Harry Potter", author: "JK Rowling"}, {name: "Hunger Games", author: "Suzanne Collins"}, {name: "Lord of the Rings", author: "J. R. R. Tolkien"}, {name: "Game of Thrones", author: "George R.R. Martin"}, {name: "Percy Jackson", author: "Rick Riordan"}, ]; // 创建ul元素并添加到页面 let myUL = document.createElement("UL"); myUL.setAttribute("id", "myUL"); document.getElementById("myDiv").appendChild(myUL); // 遍历对象数组生成li for (const item of myObj) { const li = document.createElement("LI"); // 填充li的内容,将作者名加粗 li.innerHTML = `<strong>${item.author}</strong>: ${item.name}`; // 将li添加到ul中 myUL.appendChild(li); }
关键修改点:
- 循环中先创建单个
<li>元素并保存到变量,避免重复调用DOM创建方法 - 使用
innerHTML直接构建包含<strong>标签的内容,快速实现目标格式 - 直接复用已创建的
myUL变量添加子元素,无需每次通过getElementById查询,提升性能
内容的提问来源于stack exchange,提问作者nb_nb_nb
相关产品推荐
相关产品推荐

