我正在编写一个程序,该程序从 API 调用以获取随机的猫图像。我希望能够在我的网页上显示该图像,而不仅仅是在控制台中显示网址。
//这是我的 html(这确实很基本,但我只想让输出正常工作)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cat Gif</title>
</head>
<body>
<div class="container">
<h1>This is a random image of a cat!</h1>
</div>
<script src="catGif.js">
</script>
</body>
</html>
//这是我的 JavaScript
let container = document.querySelector(".container");
async function apiFunction() {
await fetch("https://api.thecatapi.com/v1/images/search")
.then(res => res.json())
.then((result) => {
//items = result;
let img = document.createElement("img");
img.src = result[0].url;
container.appendChild(img);
}),
(error) => {
console.log(error);
}
} Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号