0

嗨,这可能很容易,但我是新手,刚刚学习我需要帮助解决 2 个问题。

首先,在使用document.createElement()如何向该元素添加类或 id 创建元素时?

----找到了解决这个问题的方法,className = ""或者id=""通过添加一个变量来区分来自我添加并命名为id的数组的数据----

二、使用createTextNode()避免使用innerHTML如何在里面添加换行符标签?

可以说我有一个数组items = [{id: "item-1", name: "apple", price:1} , {id:"item-2" ,name : "mango", price:3}];

我想通过它们:

let data = document.getElementById("items-data"); 
items.forEach(item => {
                   let container = document.createElement("div"),  //here i want to add a defined id for further use
                       itemData = document.createTextNode(
                                  `item name : ${item.name} price: ${item.price}`); //here i want to add the br
    container.appendChild(itemData);
    container.id = item.id;
    data.appendChild(container);
};
4

1 回答 1

1

你的意思是这样的:

container.appendChild(document.createElement("br"));

let base = document.querySelector(".base");

let items = [{
  id: "item-1",
  name: "apple",
  price: 1
}, {
  id: "item-2",
  name: "mango",
  price: 3
}];

items.forEach(item => {
  let container = document.createElement("div"), //here i want to add a defined id for further use
    itemData = document.createTextNode(
      `item name : ${item.name} price: ${item.price}`); //here i want to add the br
  container.appendChild(itemData);
  container.appendChild(document.createElement("br")); // <-- Add the line break to the node element
  container.id = item.id;
  base.appendChild(container);
});
<div class="base"></div>

于 2020-06-27T14:48:08.850 回答