Best way to display default image if specified image file is not found?

后端 未结 6 2119
清歌不尽
清歌不尽 2021-02-04 06:12

I\'ve got your average e-Commerce app, I store ITEM_IMAGE_NAME in the database, and sometimes managers MISSPELL the image name.

To avoid \"missing images\" (red X in IE

6条回答
  •  感动是毒
    2021-02-04 07:10

    I like Erik's solution, but without removing the event after the first execution, because if you are using that code in, let's say, an MVC partial view, this will work only the first time it is loaded. So I'd go with:

    
    

    In case you have many images in the same situation, like a grid, you can do this instead:

    $("img").on("error", function () {
        $(this).attr('src', 'default.jpg');
    });
    

    Of course, you may want to use a more specific jQuery selector.

提交回复
热议问题