我已经从称为Randomuser的API提取了数据,该API将包含图像的随机用户传递给它。我选择了5个随机用户的姓名和电话号码。
包含图像但图像是必须随机分配的同一图像。
有什么方法可以随机化图像吗?
我的代码:
fetch('https://randomuser.me/api/?results=5&nat=us').then(response => {
return response.json();
}).then(responseJson => {
responseJson.results
console.log(responseJson);
for (const user of responseJson.results) {
const img = document.createElement("IMG");
img.innertext = user.picture.medium;
-- > img.setAttribute("src", "img.setAttribute("
src ", "
https: //randomuser.me/api/portraits/thumb/men/5.jpg")")
img.setAttribute("width", "50"); img.setAttribute("height", "50"); img.setAttribute("alt", ""); document.body.appendChild(img)
console.log(user);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 0 :(得分:0)
您必须替换:
img.setAttribute("src", "img.setAttribute("src",
“ https://randomuser.me/api/portraits/thumb/men/5.jpg”)“)
通过:
img.setAttribute("src", user.picture.medium);
示例示例:
$.get('https://randomuser.me/api/?results=5&nat=us', function(responseJson) {
for (const user of responseJson.results) {
const img = document.createElement("IMG");
img.innertext = user.picture.medium;
img.setAttribute("src", user.picture.medium);
img.setAttribute("width", "50");
img.setAttribute("height", "50");
img.setAttribute("alt", "");
document.body.appendChild(img);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>