代码之家  ›  专栏  ›  技术社区  ›  steve

图像加载失败时检测

  •  2
  • steve  · 技术社区  · 6 年前

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

    // 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 回复  |  直到 6 年前
        1
  •  4
  •   Rory McCrossan Hsm Sharique Hasan    6 年前

    你的问题是因为 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" />

    如果你有 在页面加载后动态附加到DOM的元素,您需要在创建时手动将此事件处理程序绑定到这些元素。

        2
  •  1
  •   John McCollum    6 年前

    根据你的小提琴,这应该管用:

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