【发布时间】:2020-06-20 05:44:28
【问题描述】:
我正在尝试使用 fetch 从 api 获取数据,循环遍历数据并将它们呈现为动态创建 html 元素和属性。这是我的代码
fetch('https://get_products')
.then((response) => {
return response.json();
})
.then((item) => {
data = item.data
console.log(data)
if (data && data.length > 0) {
data.map((item) => {
console.log(item)
var store = document.getElementsByClassName('Store')
var ul = document.createElement("ul").classList.add("ProductGrid")
var li = document.createElement("li").classList.add("ProductGrid_item")
var a = document.createElement("a")
var divCard = document.createElement("div").classList.add("ProductCard")
var divImg = document.createElement("div").classList.add("ProductCard_image")
var img = document.createElement("img").src = item.photo
var divInfo = document.createElement("div").classList.add("ProductCard_info")
var h5 = document.createElement("h5").classList.add("ProductCard_name")
var name = document.createTextNode(item.name)
var p = document.createElement("p").classList.add("ProductCard_price")
var price = document.createTextNode(item.proce)
store.appendChild(ul)
li.appendChild(a)
a.appendChild(divCard)
divCard.appendChild(divImg)
divImg.appendChild(img)
divCard.appendChild(divInfo)
divInfo.appendChild(h5)
divInfo.appendChild(p)
p.appendChild(price)
h5.appendChild(name)
})
}
})
当我运行 JavaScript 文件时,我的控制台中出现错误
index.js:76 Uncaught (in promise) TypeError: store.appendChild is not a function
at index.js:76
at Array.map (<anonymous>)
at index.js:60
不知道哪里做错了。
【问题讨论】:
-
是什么让你认为
store.appendChild是一个函数?
标签: javascript html arrays dom dom-manipulation