如何在javascript中加载多个图像时保持索引的状态

时间:2014-01-09 12:00:32

标签: 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";
    }

    imageArray[i].onerror = function() {
      alert("not loaded");
    }

    imageArray[i].src = '/home//dummy_'+i+'.jpg';

  }

我想从虚拟图像列表中加载一些图像。 但在onload期间我失去了我的背景, 它总是指向i = 3(循环的最后一个值)。 为了保护这个我,所以当涉及到onload时,它会给我一个确切的。

1 个答案:

答案 0 :(得分:1)

您需要将其包装在另一个函数中:

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来...将参数绑定到您的函数:

imageArray[i].onload = function(i,event) { 
// added the event parameter to show that the arguments normally passed to the function are not overwritten, merely pushed to make room for the bound ones
      $("#cell_"+i).append(imageArray[i]);
      imageArray[i].style.visibility = "hidden";
    }
}.bind(null, i); // the function will always be called with he value of i passed to the first argument

注意:在幕后,这是同样的解决方案。

参考: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind