javascript Jquery on image error 不适用于动态图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18683503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:52:33  来源:igfitidea点击:

Jquery on image error not working on dynamic images?

javascriptjquery

提问by user960567

I have the following js code,

我有以下js代码,

 $(document).on("error", "img", function () {
            alert('a')
            this.src = ResolveUrl("~/images/tree-item.png");
        });

This event is not triggered. I am sure there are lot of broken images

不会触发此事件。我确定有很多破碎的图像

回答by Itay

The problem is that you can't use event delegationfor the errorevent on the document object, because unlike other events (such as onclick), the onerrorevent isn't being bubbled to the document object.

问题是您不能event delegation用于error文档对象上的事件,因为与其他事件(例如onclick)不同,该onerror事件不会冒泡到文档对象。

Use normal event binding instead:

改用普通事件绑定:

$('img').on("error", function () {
    this.src = ResolveUrl("~/images/tree-item.png");
});
  • P.S - This will work only on the images that are already on the DOM when this command is executed.
  • PS - 这仅适用于执行此命令时已在 DOM 上的图像。


To handle dynamically added images as well, you need to attach this event to every image you add to the DOM. Here's an example:

为了处理动态添加的图像,您需要将此事件附加到您添加到 DOM 的每个图像。下面是一个例子:

function handleError() {
    this.src = ResolveUrl("~/images/tree-item.png");
}

// Bind the event to the existing images on the DOM when the document is ready
$(document).ready(function () {
    $('img').on("error", handleError);
}

// An example for a function that adds images dynamically
function addImage(imgSource, destination) {
    var newImg = $("img").on("error", handleError)
                         .attr("src", imgSource);

    $(destination).append(newImg);
}

回答by bernhardh

I know, its an old question, but maybe someone is looking for a better solution:

我知道,这是一个老问题,但也许有人正在寻找更好的解决方案:

// The function to insert a fallback image
var imgNotFound = function() {
    $(this).unbind("error").attr("src", "/path/to/fallback/img.jpg");
};
// Bind image error on document load
$("img").error(imgNotFound);
// Bind image error after ajax complete
$(document).ajaxComplete(function(){
    $("img").error(imgNotFound);
});

This code attaches the error-event listener to the img tag on body load and after every ajax call.

此代码在主体加载时和每次 ajax 调用之后将错误事件侦听器附加到 img 标记。