我有以下js代码,
$(document).on("error", "img", function () {
alert('a')
this.src = ResolveUrl("~/images/tree-item.png");
});
此事件未触发。我敢肯定有很多破碎的图像
我有以下js代码,
$(document).on("error", "img", function () {
alert('a')
this.src = ResolveUrl("~/images/tree-item.png");
});
此事件未触发。我敢肯定有很多破碎的图像
问题是您不能event delegation
将error
事件用于文档对象上的事件,因为与其他事件(例如onclick
)不同,该onerror
事件不会冒泡到文档对象。
改用普通事件绑定:
$('img').on("error", function () {
this.src = ResolveUrl("~/images/tree-item.png");
});
要同时处理动态添加的图像,您需要将此事件附加到您添加到 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);
}
我知道,这是一个老问题,但也许有人正在寻找更好的解决方案:
// 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);
});
此代码在正文加载时和每次 ajax 调用之后将错误事件侦听器附加到 img 标记。