Javascript:将函数作为参数传递 [英] Javascript : passing a function as an argument

查看:111
本文介绍了Javascript:将函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果图像无法加载,我想加载默认图像.我也想打电话 加载图像后,将执行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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆