如何在javaScript中动态生成图像并在网页加载后显示?



我想从数组中获取图像,并在浏览器窗口加载后显示在网页上。这就是我所做的。

const players = [
{
photo: 'img/photo0.jpeg'
},
{
photo: 'img/photo1.jpeg'
},
{
photo: 'img/photo2.jpeg'
}]
// This is the function I built to do that.
function() {
for(i = 0; i < players.lengh; i++;){
}
}

可以通过window对象访问onLoad方法。

window.onload = function() {
// Whatever you want to do on load
};

let box = document.querySelector(".box");
const players = [
{
photo: "img/photo0.jpeg",
},
{
photo: "img/photo1.jpeg",
},
{
photo: "img/photo2.jpeg",
},
];
function displayImages() {
// Empty the box element so, that if some changes made to this element will reflect new data
box.innerHTML = ``;
// create template to show
let domStr = ``;
for (let img of players) {
//dynamic creating images in template str
domStr += `
<img src=${img.photo} width=200 height=200>
`;
}
// after loop concatenates str with img in loop make it attach with the element
// document.body.innerHTML = domStr;
box.innerHTML = domStr;
}
//   On window load calling the function
window.addEventListener("load", (event) => {
displayImages();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div class="box"></div>
</body>
</html>

最新更新