从数组对象创建无序列表

问题描述 投票:0回答:2

我想使用 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>

不知道如何使我的列表看起来像:

  • JK 罗琳:哈利·波特
  • 苏珊·柯林斯:饥饿游戏
  • J。 R.R.托尔金:指环王
  • 乔治·R·R·马丁:权力的游戏
  • 瑞克·赖尔登:珀西·杰克逊

使用普通 JS

javascript list for-loop appendchild createelement
2个回答
2
投票

您应该使用

createElement
创建一个
<strong>
标签,并在其中放置
item.author

然后使用 item.name

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>


-1
投票

要创建所需的无序列表,请按如下方式更新 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>

© www.soinside.com 2019 - 2024. All rights reserved.