我如何分配图像的链接,我得到与API图像的src ?



我不能将我使用API获得的图像链接分配给图像的src。我正在使用fetch获取信息,(我是新的api)。

fetch("https://restcountries.com/v3.1/all")
.then(respons => respons.json())
.then(b => {
let pic = b[0].flags.png;
document.getElementById("img").src =  "pic";
})
<img src="" alt="" id="img">

您的代码有问题。您创建了名为pic的变量。但不是分配变量给src,而是分配"pic"字符串。正确的代码是:

fetch("https://restcountries.com/v3.1/all")
.then(respons => respons.json())
.then(b => {
let pic = b[0].flags.png;
document.getElementById("img").src =  pic;
})

请注意,我从pic变量中删除了引号。

最新更新