I am new to JavaScript and therefore am confused in the field of variables ... I try to load an image and replace it with a different url when it does not exist. I have to do this in pure JavaScript.
Here I got two versions, very similar, but they work differently. The only thing in common: they do not work. The third version requires updating and does not work under IE. d is an object with the number attribute that has no problem.
That's what they have in common
.attr("xlink:href", function (d) {
var img = new Image();
Version 1 is called here: both onload
and onerror
. However, d gets src, unfortunately it is always 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;
}
Here is version 2: Depending on the existence of the image, either onload or onerror is called. But the value of d.src is undefined when notified.
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);
return d.src;
}
3: , . , . , , .
img.src = "http://.../peopleimages/" + d.num + ".jpg";
return img.complete ? "http://.../peopleimages/" + d.num + ".jpg" : "http://.../images/generic.jpg";
}