【发布时间】:2019-06-07 08:50:27
【问题描述】:
我有一个 api,它由一个对象组成,该对象包含嵌套在其中的 jpeg 链接数组。我想将每个图像渲染到 HTML 文档中,但是我得到一个错误
index.js:19 Uncaught (in promise) TypeError: Cannot read property 'forEach' 的未定义 在 addDogs (index.js:19) 在 index.js:30
我假设一旦我们使用链接获取对象,我们就会提取该对象内的 jpeg 链接数组并对其执行 forEach() 方法。但是似乎我错了,有人可以帮我吗?我的代码如下,包括 HTML 文档、JavaScript 代码和实际的 api。
HTML 文件
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Intro to AJAX Practice Tasks</title>
<script src="src/index.js" charset="utf-8"></script>
</head>
<body>
<h1>Dog CEO</h1>
<div id="dog-image-container">
<!-- images here -->
</div>
<hr>
<label for="select-breed">Filter Breeds That Start with:</label>
<select id="breed-dropdown" name="select-breed">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<ul id="dog-breeds">
</ul>
</body>
</html>
JavaScript
const imgUrl = "https://dog.ceo/api/breeds/image/random/4"
const dogsContainer = document.getElementById("dog-breeds")
function addDog(dog) {
const tr = document.createElement('tr')
tr.innerHTML = `<img src = ${dog.message} >`
dogsContainer.append(tr)
}
function addDogs(dogs) {
for (const key in dogs) {
const dogImages = dogs[key]
dogImages.message.forEach((dog) => addDog(dog))
}
}
function getDogs() {
return fetch(imgUrl)
.then((response) => response.json())
}
getDogs()
.then((dogs) => addDogs(dogs))
API(JSON)
{
"status": "success",
"message": [
"https://images.dog.ceo/breeds/komondor/n02105505_4290.jpg",
"https://images.dog.ceo/breeds/schipperke/n02104365_8190.jpg",
"https://images.dog.ceo/breeds/entlebucher/n02108000_3306.jpg",
"https://images.dog.ceo/breeds/keeshond/n02112350_6861.jpg"
]
}
【问题讨论】:
-
您的内联
<img>元素看起来有点乱(没有<table>,没有<td>,没有属性引号,没有src属性值的HTML 编码)。我会选择const img = document.createElement('img'); img.src = dog;。我还会创建一个<td>并将图像附加到该
标签: javascript