javascript - javascript中的dom操作和获取
问题描述
我正在尝试使用 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
不知道做错了什么。
解决方案
你需要获取元素,因为所有这个函数都返回元素数组
var store = document.getElementsByClassName('Store')[0];
在所有其他情况下也是第一个元素或循环集合
推荐阅读
- aws-codecommit - 多账户代码提交设置 aws
- angular - 如何在角度 5 的嵌套 json 数组中发布值?
- python - Tkinter Python OOP:使用 canvas.move() 一次移动单独的小部件
- ssl - IIS 8 基于 URL 地址重定向到 HTTPS
- java - 在等待 Swing 对话框结果时阻塞 JavaFX
- php - 从输入表单到 C 源代码,检查不允许的关键字
- nlp - 查询映射到 NLIDB 系统中的数据库
- ruby-on-rails - 如何在 AWS lightsail 中无错误地在 Rails DB 上创建 ruby
- css - Adblock plus:如何反转 :-abp-has() 选择器?
- node.js - 无法使用 express-fileupload 上传文件