我想使用 vanilla JS 创建一个无序列表,从对象数组创建一个列表。不知道该怎么做。
这是我当前的代码:
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"},
];
console.log(myObj);
let myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");
document.getElementById("myDiv").appendChild(myUL);
for (const item of myObj) {
document
.getElementById("myUL")
.appendChild(document.createElement("LI"));
}
<div id="myDiv"></div>
不知道如何使我的列表看起来像:
使用普通 JS
createElement
创建一个 <strong>
标签,并在其中放置 item.author
。
为 document.createTextNode
创建一个新的 文本节点
然后 将 textNode 附加到
li
并将其附加到 ul
:
const 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"},
];
const myUL = document.createElement("UL");
myUL.setAttribute("id", "myUL");
const ul = document.getElementById("myDiv").appendChild(myUL);
for (const item of myObj) {
let author = document.createElement("strong");
author. textContent = item.author + ': ';
let li = document.createElement("li");
li.appendChild(author);
li.appendChild(document.createTextNode(item.name))
ul.appendChild(li);
}
<div id="myDiv"></div>
要创建所需的无序列表,请按如下方式更新 js:
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" },
];
let myUL = document.createElement("ul");
myUL.setAttribute("id", "myUL");
for (const item of myObj) {
let listItem = document.createElement("li");
listItem.textContent = `${item.author}: ${item.name}`;
myUL.appendChild(listItem);
}
document.getElementById("myDiv").appendChild(myUL);
在修改后的代码中,创建了一个
li
元素,然后将其附加到 ul
元素。如果您希望名称以粗体显示,可以使用 <strong>
或 <b>