Jquery图像错误不适用于动态图像?

use*_*567 18 javascript jquery

我有以下js代码,

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

此事件未触发.我相信有很多破碎的图像

Ita*_*tay 22

问题是,你不能使用event delegationerror文档对象的事件,因为不像其他事件(如onclick),该onerror事件不会冒泡文档对象.

改为使用普通事件绑定:

$('img').on("error", function () {
    this.src = ResolveUrl("~/images/tree-item.png");
});
Run Code Online (Sandbox Code Playgroud)
  • PS - 执行此命令时,这仅适用于DOM上已有的图像.

要处理动态添加的图像,您需要将此事件附加到添加到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);
}
Run Code Online (Sandbox Code Playgroud)

  • 应在定义源属性之前完成附加处理程序. (4认同)

ber*_*rdh 6

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

// 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);
});
Run Code Online (Sandbox Code Playgroud)

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