Javascript:将函数作为参数传递

时间:2013-10-28 19:33:42

标签: javascript onerror

如果图片无法加载,我想加载默认图片。我也想打电话 加载图像后getLoadComplete()。如何将this.getLoadComplete()函数传递给img.onerror上调用的函数?

以下是我的代码:

    img.onload = this.getLoadComplete();

    img.onerror = function(){
        img.src = "http://xxxx.com/image.gif";
     }

     img.src = request.url;

2 个答案:

答案 0 :(得分:3)

img.onload = this.getLoadComplete();

您立即调用getLoadComplete(),并将其返回值分配给img.onload。你可能想要这个:

img.onload = this.getLoadComplete;

即,将img.onload设置为函数本身,而不是其返回值。

您无需在onerror中做任何特别的事情; onload处理程序将仍然设置为getLoadComplete,当您修改src处理程序中的onerror时,它将调用{{1}加载后备图像后。

答案 1 :(得分:0)

你只需要调用该函数。

img.onload = this.getLoadComplete();

img.onerror = function(){
    img.src = "http://www.3d-maps-minus-3d.com/img/unavailable.gif";
this.getLoadComplete();
 }