Javascript: onload函数调用了两次
Javascript: onload function called twice
Transition.start = function(){
for(var j = 0; j < 6; j++)
{
console.log("FOR LOOP");
(function(){
console.log("INNER Function");
var image = new Image();
image.src = path + Config.imgName[j] + ".jpg";
image.onload = function () {
console.log("GONE");
clearImages[source].push(image);
console.log(image);
};
})();
}
}
在控制台上 "FOR LOOP" 和 "INNER Function" 打印了 6 次,但是 "GONE" 打印了 12 次。我无法弄清楚这是为什么。我想运行 body of onload也6次
和 Transition.start
是从 onDocumentKeyDown
侦听器中调用的
function onDocumentKeyDown( event )
{
if (keyPressed == 38) //up arrow
Transition.start();
}
我找到了问题的根源。实际上 image.onload
每次在浏览器中呈现图像时都会被调用。实际上,我一旦加载了图像,就将其存储在 clearImages
中,这样如果将来需要图像,就可以直接从该数组中获取图像,因此如果将来需要图像,则可以从 clearImages
数组,但将再次调用 onload 函数。
所以我通过在onload
函数本身
中执行image.onload = null
解决了这个问题
Transition.start = function(){
for(var j = 0; j < 6; j++)
{
console.log("FOR LOOP");
(function(){
console.log("INNER Function");
var image = new Image();
image.src = path + Config.imgName[j] + ".jpg";
image.onload = function () {
console.log("GONE");
clearImages[source].push(image);
console.log(image);
};
})();
}
}
在控制台上 "FOR LOOP" 和 "INNER Function" 打印了 6 次,但是 "GONE" 打印了 12 次。我无法弄清楚这是为什么。我想运行 body of onload也6次
和 Transition.start
是从 onDocumentKeyDown
侦听器中调用的
function onDocumentKeyDown( event )
{
if (keyPressed == 38) //up arrow
Transition.start();
}
我找到了问题的根源。实际上 image.onload
每次在浏览器中呈现图像时都会被调用。实际上,我一旦加载了图像,就将其存储在 clearImages
中,这样如果将来需要图像,就可以直接从该数组中获取图像,因此如果将来需要图像,则可以从 clearImages
数组,但将再次调用 onload 函数。
所以我通过在onload
函数本身
image.onload = null
解决了这个问题