我想替换我网站上所有无效图像的 src
。
我的网站上有很多动态内容,所以我想出了这个简单的代码:
$(document).on("error", "img", function (e) {
var $element = $(e.currentTarget);
$element.attr("src", "images/oops.png");
});
但它没有被调用。同样的方法适用于点击事件(以及许多其他类型的事件)。
最佳答案
这应该有用(它对我有用;D)
jQuery("<img />")
.on('load', function() {
//this are correct
})
.on('error', function() {
//here the error
})
.attr("src", urlToComprobate);
你可以在jsfiddle中尝试一下:https://jsfiddle.net/87wkf0cc/
当您创建 DOM 图像(使用 jQuery("<img />")
)时为空,当您强制加载时(使用 attr
)可以检查 url 是否存在
关于javascript - img 动态内容的错误事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035350/