Javascript:将函数作为参数传递 [英] Javascript : passing a function as an argument
问题描述
如果图像无法加载,我想加载默认图像.我也想打电话 加载图像后,将执行getLoadComplete().如何将this.getLoadComplete()函数传递给在img.onerror上调用的函数?
这是我得到的代码:
img.onload = this.getLoadComplete();
img.onerror = function(){
img.src = "http://xxxx.com/image.gif";
}
img.src = request.url;
img.onload = this.getLoadComplete();
您将立即调用getLoadComplete()
,并将其返回值分配给img.onload
.您可能想要这样:
img.onload = this.getLoadComplete;
也就是说,将img.onload
设置为函数本身,而不是其返回值.
您无需在onerror
中做任何特别的事情; onload
处理程序将 still 设置为getLoadComplete
,并且当您在onerror
处理程序中修改src
时,将在加载后备图像后调用onload
./p>
I want to load a default image if an image fails to load. I also want to call getLoadComplete() once the image has loaded. How do I pass the this.getLoadComplete() function into the function called on img.onerror?
Here is the code I've got:
img.onload = this.getLoadComplete();
img.onerror = function(){
img.src = "http://xxxx.com/image.gif";
}
img.src = request.url;
img.onload = this.getLoadComplete();
You're invoking getLoadComplete()
immediately, and assigning its return value to img.onload
. You probably want this:
img.onload = this.getLoadComplete;
That is, set img.onload
to the function itself, not its return value.
You don't need to do anything special in onerror
; the onload
handler will still be set to getLoadComplete
, and when you modify the src
in your onerror
handler, it will invoke onload
after the fallback image is loaded.
这篇关于Javascript:将函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!