如何将图像加载到对象并在错误时设置默认值



我有容器,我应该在其中加载图像。图像具有每个id唯一的实际图像。如果该 id 不存在图像,则它应该加载默认图像。这是我拥有的示例:

function addImage() {
    var image = new Image();
    image.addEventListener('load', function () {
        this.src = 'images/'+id+'_image01.jpg';
    });
    image.addEventListener('error', function (e) {
        // Image not found, show the default
        image.src = 'images/default.jpg';
    });
    image.width = 233;
    console.log(image);
 }

控制台中上述函数的输出如下所示:

<img width="233">

附加到图像对象的唯一属性是 width 。我想知道为什么不附加源。它应该看起来像这样:

<img width="233" src="images/89_image01.jpg"> //Image exist

或者如果图像不存在,则这样做:

<img width="233" src="images/default.jpg"> //Image does not exist

我不确定为什么我的函数只附加宽度。如果有人能检测到问题,请告诉我。

您需要在

onload 事件处理程序之外将 src 属性添加到图像对象,以便它实际调用该事件处理程序或调用 onerror 事件处理程序。

function addImage(id) {
var image = new Image();
image.addEventListener('error', function onError (e) {
    // Image not found, show the default
    image.removeEventListener(error, onError);
    image.src = 'images/default.jpg';
});
image.width = 233;
image.src = 'images/'+id+'_image01.jpg';
console.log(image);

}

另外,不要忘记在加载默认图像后删除 onError 事件处理程序,如果未找到默认图像,这将节省一些麻烦。

最新更新