I'm currently trying to display a picture on my html. I'm using an api from newsapi.org I have figured out how to show the author, the headline etc. But the picture i cannot display. I have tried to use an onload function which i'm not sure if i need. Please let me know if it does not matter. This is what my javascript looks like:
const url = "https:newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=xxxxxx";
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(data)
let show = () => {
let img = document.getElementById("img");
img.src = data.articles[0].urlToImage;
let img1 = document.getElementById("img1");
img1.src = data.articles[1].urlToImage;
let img2 = document.getElementById("img2");
img2.src = data.articles[2].urlToImage;
}
});
This is what my html looks like:
<html lang="en">
<head>
<script src="news.js"></script>
<link rel="stylesheet" href="test.css" />
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<img id="img" onload="show()" alt="news">
<img id="img1" onload="show()" alt="news">
<img id="img2" onload="show()" alt="news">
</body>
</html>
Answers are greatly appreciated!
I cannot test the code myself as you're using an API key that I don't have but it seems like you're returning a show
function that does not get called anywhere, so nothing happens.
const url = "https:newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=xxxxxx";
fetch(url)
.then((response) => response.json())
.then((data) => {
let img = document.getElementById("img");
img.src = data.articles[0].urlToImage;
let img1 = document.getElementById("img1");
img1.src = data.articles[1].urlToImage;
let img2 = document.getElementById("img2");
img2.src = data.articles[2].urlToImage;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.