Javascript : passing a function as an argument

不羁岁月 提交于 2019-12-13 05:48:08

问题


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;

回答1:


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.




回答2:


you just need to call the function.

img.onload = this.getLoadComplete();

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


来源:https://stackoverflow.com/questions/19643528/javascript-passing-a-function-as-an-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!