如何在javascript中加载多个图像时保持索引状态 var-imageArray=[]; 对于(var i=0;i
您需要将其包装在另一个函数中:如何在javascript中加载多个图像时保持索引状态 var-imageArray=[]; 对于(var i=0;i,javascript,Javascript,您需要将其包装在另一个函数中: var imageArray = []; for(var i =0; i<3; i++){ imageArray[i] = new Image(); imageArray[i].onload = function(i) { $("#cell_"+i).append(imageArray[i]); imageArray[i].style.visibility = "hidden"; } image
var imageArray = [];
for(var i =0; i<3; i++){
imageArray[i] = new Image();
imageArray[i].onload = function(i) {
$("#cell_"+i).append(imageArray[i]);
imageArray[i].style.visibility = "hidden";
}
imageArray[i].onerror = function() {
alert("not loaded");
}
imageArray[i].src = '/home//dummy_'+i+'.jpg';
}
imageArray[i].onload = function(ic) { // ic is a copy of i in the scope of this function
return function() {
$("#cell_"+ic).append(imageArray[ic]); // ic is borrowed from the outer scope
imageArray[ic].style.visibility = "hidden";
}
}(i); // call the function with i as parameter
或者,您可以使用bind to…将参数绑定到函数:
var imageArray = [];
for(var i =0; i<3; i++){
imageArray[i] = new Image();
imageArray[i].onload = function(i) {
$("#cell_"+i).append(imageArray[i]);
imageArray[i].style.visibility = "hidden";
}
imageArray[i].onerror = function() {
alert("not loaded");
}
imageArray[i].src = '/home//dummy_'+i+'.jpg';
}
imageArray[i].onload = function(ic) { // ic is a copy of i in the scope of this function
return function() {
$("#cell_"+ic).append(imageArray[ic]); // ic is borrowed from the outer scope
imageArray[ic].style.visibility = "hidden";
}
}(i); // call the function with i as parameter
注意:在幕后,这是相同的解决方案
参考: