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 delegation
的error
文档对象的事件,因为不像其他事件(如onclick
),该onerror
事件不会冒泡文档对象.
改为使用普通事件绑定:
$('img').on("error", function () {
this.src = ResolveUrl("~/images/tree-item.png");
});
Run Code Online (Sandbox Code Playgroud)
要处理动态添加的图像,您需要将此事件附加到添加到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)
我知道,这是一个老问题,但也许有人正在寻找更好的解决方案:
// 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 标记。
归档时间: |
|
查看次数: |
13943 次 |
最近记录: |