代码之家  ›  专栏  ›  技术社区  ›  espresso_coffee

如何将图像加载到对象并设置默认值(如果出错)?

  •  -1
  • espresso_coffee  · 技术社区  · 6 年前

    我有装图像的容器。该图像具有每个图像所特有的实际图像 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
    

    或者这个IF图像不存在:

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

    我不知道为什么我的函数只附加宽度。如果有人能发现这个问题,请告诉我。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Richard Roncancio    6 年前

    您需要在onload事件处理程序外部之后将src属性添加到image对象,以便它实际调用该事件处理程序或调用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事件处理程序,如果找不到默认映像,这将避免一些麻烦。