[英]Looping through images array and showing them to HTML page
I'm facing issues with my JS code and I hope you guys can help me help me.我的 JS 代码遇到了问题,希望你们能帮助我。 All I want to do is loop 5 images stored in an array, and post them to my HTML page, basically.我想要做的就是循环存储在数组中的 5 个图像,并将它们发布到我的 HTML 页面,基本上。
JS: JS:
function functieArray(){
for (i = 0; i < imgArray.length; i++) {
imgArray[i];
}
document.getElementById("pozeGallery").innerHTML = imgArray.src;
};
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = 'img/Gallery/poza0.jpg';
imgArray[1] = new Image();
imgArray[1].src = 'img/Gallery/poza1.jpg';
imgArray[2] = new Image();
imgArray[2].src = 'img/Gallery/poza2.jpg';
imgArray[3] = new Image();
imgArray[3].src = 'img/Gallery/poza3.jpg';
imgArray[4] = new Image();
imgArray[4].src = 'img/Gallery/poza4.jpg';
HTML: HTML:
<button onclick='functieArray()' class='galleryButons'>Category 1</button>
<div id='pozeGallery'> </div>
You need to actually append them to the DOM for them to show up.您需要将它们实际附加到 DOM 中才能显示出来。
use the appendChild()
method使用appendChild()
方法
In your case:在你的情况下:
function functieArray() {
var gallery = document.getElementById("pozeGallery");
for (i = 0; i < imgArray.length; i++) {
gallery.appendChild(imgArray[i]);
}
};
Also note that in your code sample you are not calling functieArray
anywhere so it might not work.另请注意,在您的代码示例中,您没有在任何地方调用functieArray
,因此它可能不起作用。
To get the HTML of the Image
objects, use Image#outerHTML
.要获取Image
对象的 HTML,请使用Image#outerHTML
。 Then you can just loop through the array adding to the gallery's innerHTML
.然后你可以循环遍历添加到画廊的innerHTML
的数组。
Here is how you should fix your code (I'm going to use a loop for creating the Image
objects):以下是您应该如何修复代码(我将使用循环来创建Image
对象):
var imgArray = []; for (i = 0; i < 5; i++) { imgArray[i] = new Image(); imgArray[i].src = 'img/Gallery/poza' + i + '.jpg'; } function functieArray() { var images = imgArray.map(img => img.outerHTML).join(''); document.getElementById("pozeGallery").innerHTML = images; }
<button onclick='functieArray()' class='galleryButons'>Category 1</button> <div id='pozeGallery'></div>
Try this ;)尝试这个 ;)
function functieArray() { var gallery = document.getElementById("pozeGallery"); for (i = 0; i < imgArray.length; i++) { gallery.appendChild(imgArray[i]); } }; var imgArray = new Array(); imgArray[0] = new Image(); imgArray[0].src = 'img/Gallery/poza0.jpg'; imgArray[1] = new Image(); imgArray[1].src = 'img/Gallery/poza1.jpg'; imgArray[2] = new Image(); imgArray[2].src = 'img/Gallery/poza2.jpg'; imgArray[3] = new Image(); imgArray[3].src = 'img/Gallery/poza3.jpg'; imgArray[4] = new Image(); imgArray[4].src = 'img/Gallery/poza4.jpg';
<button onclick='functieArray()' class='galleryButons'>Category 1</button> <div id='pozeGallery'> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.