我想從一個數組中獲取圖像,并在瀏覽器窗口加載后顯示在網頁上。這就是我所做的。
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++;){
}
}
您可以通過窗口對象訪問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>