我一直在撞墙,似乎无法找到解决方案,检查其他帖子的警告相同,没有答案帮助/可以应用于我的问题。基本上很多小图片和我点击的图片在另一个地方也变得很大。
错误在第53行,也就是最后一行。
var images = new Array();
var imageThumbs = [
{"src": "images/img01thumb.jpg", "alt":"City of DU", "title":"City"},
{"src": "images/img02thumb.jpg", "alt":"Some txt", "title":"Some txt"},
{"src": "images/img03thumb.jpg", "alt":"City of DU", "title":"City"},
];
var bigImgHolder = document.createElement("div");
bigImgHolder.setAttribute("id", "bigImgHolder");
document.body.appendChild(bigImgHolder);
var elem = document.createElement("img");
elem.setAttribute("src", "images/img01.jpg");
elem.setAttribute("alt", "Big Picture!");
elem.setAttribute("id", "bigImg");
document.getElementById("bigImgHolder").appendChild(elem);
var imgHolder = document.createElement("div");
imgHolder.setAttribute("id", "imgHolder");
document.body.appendChild(imgHolder);
var elem2;
for(var i = 0; i<imageThumbs.length; i++) {
elem2 = document.createElement("img");
elem2.setAttribute("src", imageThumbs[i].src);
elem2.setAttribute("alt", imageThumbs[i].alt);
elem2.setAttribute("class", "thumb");
elem2.addEventListener("click", function(){
changeMe(i+1);
})
document.getElementById("imgHolder").appendChild(elem2);
}
function preload() {
var path = "images/";
for (var i = 1; i <= imageThumbs.length; i++) {
images[i] = new Image();
if(i<10){
images[i].src = path + "img0" + i + ".jpg";
}
else{
images[i].src = path + "img" + i + ".jpg";
}
window.alert("image " + i + " loaded");
}
}
//swap images
function changeMe(index) {
document.getElementById('bigImg').src = images[index].src;
}
答案 0 :(得分:0)
以这种方式使用changeMe
函数参数:
function changeMe(index) {
document.getElementById('bigImg').src = images[index-1].src;
}
这背后的原因是,您可能会超出范围,发送i+1
,其中i
的范围介于0
和images.length - 1
之间,但{ {1}}成为i + 1
,它会为您提供images.length
。
答案 1 :(得分:0)
你需要解决2个问题,i
的关闭,也不要超过数组的结尾并在开始时重新开始:
尝试:
for (var i = 0; i < imageThumbs.length; i++) {
// create closure using IIFE
(function (i) {
elem2 = document.createElement("img");
elem2.setAttribute("src", imageThumbs[i].src);
elem2.setAttribute("alt", imageThumbs[i].alt);
elem2.setAttribute("class", "thumb");
// make sure we don't overshoot array length
var next = i + 1 < imageThumbs.length ? i + 1 : 0;
elem2.addEventListener("click", function () {
changeMe(next);
});
document.getElementById("imgHolder").appendChild(elem2);
})(i);
}