javascript: onload and onerror called together

折月煮酒 提交于 2019-11-30 23:06:24

You are calling the functions, not assigning!

img.onload = onLoadHandler();
img.onerror = onErrorHandler();

needs to be

img.onload = onLoadHandler;
img.onerror = onErrorHandler;

The problem with your second example is that the image callbacks are fired when the image loads, after your other code has been evaluated. I'm really not sure what your code accomplishes, but try something like this.

  img.onload = function () {
     alert(d.name + " : loaded");
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
     return doSomething(this, d);
  }
  img.onerror = function () {
     alert(d.name + " : failed");
     d.src = "http://.../images/generic.jpg";
     return doSomething(this, d);
  }

  function doSomething(img, d) {
     img.src = "http://.../peopleimages/" + d.num + ".jpg";
     alert(d.src);
     return d.src;
  };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!