检测何时无法加载图像

时间:2018-09-20 09:53:00

标签: javascript jquery

使用jQuery我需要在缺少图像时调用一个函数。我需要使用jquery,因为我要匹配包含特定路径的所有图像。在jquery中执行此操作比较简单。

我在网上找到了一个示例,但无法确定为什么它不起作用。任何帮助将不胜感激。

// tried this and didn't work
$(document).on('error', 'img[src*="/image/path/"]', function() {
  alert('error loading image ' + $(this).attr('src'));
});

// to rule out path condition i tried this and it also didn't work
$('body').on('error', 'img', function() {
  alert('error loading image ' + $(this).attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<img src="/my/image/path/foo/bar.jpg" />

Demo fiddle

2 个答案:

答案 0 :(得分:4)

问题的原因是因为error事件不会冒泡,因此您尝试使用的委托事件处理程序将不会从document中拾取事件。

要解决此问题,您需要使用直接在img元素上定义的静态事件处理程序:

$('img[src*="/image/path/"]').on('error', function() {
  console.log('error loading image ' + $(this).attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<img src="/my/image/path/foo/bar.jpg" />

如果您有img个元素,这些元素在页面加载后会动态添加到DOM,则需要在创建它们时手动将事件处理程序绑定到它们。

答案 1 :(得分:1)

根据您的小提琴,这应该有效:

$('img[src*="/image/path/"]').on('error', function() {
  alert('error loading image ' + $(this).attr('src'));
});
相关问题