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

时间:2013-09-08 12:08:22

标签: javascript jquery

我有以下js代码,

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

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

2 个答案:

答案 0 :(得分:20)

问题是您无法在文档对象上使用event delegation error事件,因为与其他事件(例如onclick)不同,onerror事件未被冒泡到文档对象。

改为使用普通事件绑定:

$('img').on("error", function () {
    this.src = ResolveUrl("~/images/tree-item.png");
});
  • P.S - 执行此命令时,此功能仅适用于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").attr("src", imgSource)
                         .on("error", handleError);

    $(destination).append(newImg);
}

答案 1 :(得分:4)

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

// 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);
});

此代码将错误事件侦听器附加到body load上的img标记以及每次ajax调用之后。