javascript:onload和onerror一起调用 [英] javascript: onload and onerror called together

查看:877
本文介绍了javascript:onload和onerror一起调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,因此混淆变量范围...
我试图加载一个图像,并替换为另一个URL,当它不存在。
我必须用纯JavaScript。

I'm new to JavaScript and therefore confused for the variable scope... I'm trying to load an image, and replace it with another URL when it doesn't exist. I have to do it in pure JavaScript.

这里我有两个版本非常相似,但他们的表现不同。唯一的共同点是:他们不工作。第三版需要刷新,不能在IE下工作。 d是带有number属性的对象,没有问题。

Here I got 2 versions extremely alike, but they perform differently. The only thing in common is: they don't work. The 3rd version requires a refresh and doesn't work under IE. d is the object with number attribute, which has no problem.

这是他们的共同之处

.attr("xlink:href", function (d) {
  var img = new Image();

这里的版本1: onload onerror 但是d接收到src,不幸的是它总是generic.jpg。

Here the Version 1: Both onload and onerror are called. However d receives the src, unfortunately it's always the generic.jpg.

  function onLoadHandler() {
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
     alert(d.name + " onload called");
  }
  function onErrorHandler() {
     d.src = "http://.../images/generic.jpg";
     alert(d.name + " onerror called");
  }
  img.onload = onLoadHandler();
  img.onerror = onErrorHandler();
  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  return d.src;
  }

2:根据图像的存在,调用onload或onerror。但是当警告时d.src的值是未定义的。

Here the Version 2: Depending on the existance of the image, either onload or onerror is called. But the value of d.src is undefined when alert.

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

  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  alert(d.src);//undefined
  return d.src;
  }

这里的版本3:它工作,但不是第一次。我必须做刷新才能得到正确的图像。也许它在图像完全加载之前返回。

Here the Version 3: it works but not the first time. I have to do refresh to get the images correctly. Perhaps it returns before the image is loaded completely.

  img.src = "http://.../peopleimages/" + d.num + ".jpg";
  return img.complete ? "http://.../peopleimages/" + d.num + ".jpg" : "http://.../images/generic.jpg";
  }


推荐答案

不分配!

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

需要

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

这篇关于javascript:onload和onerror一起调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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