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

我有以下js代码,

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

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

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

改为使用普通事件绑定:

 $('img').on("error", function () { this.src = ResolveUrl("~/images/tree-item.png"); }); 
  • 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").attr("src", imgSource) .on("error", handleError); $(destination).append(newImg); } 

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

 // 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调用之后。