如果图像在延迟加载图像加载后损坏,则设置图像默认值。我该怎么做?

set image default if image is broken after lazy load image loading . how i do this?

加载延迟加载后无法设置图像默认值。

$(document).ready(function() {
  function setDefaultImage(img) {
    //set default.
    img.src = "https://www.google.com/images/srpr/logo11w.png";
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="images/logo.png" onerror="setDefaultImage(this);" data-original="http://pacehold.it/600x450" class="img-responsive lazy" alt="">

只需将函数声明移出 $ 函数即可。当 $ 中的函数不在 window 的上下文中时,因此 html 无法访问它。当您将其移出时,您可以使用 window.setDefaultImage(在 console 中尝试)访问它,因此 html.

//function setDefaultImage(img) {
  //set default.
  //img.src = "https://www.google.com/images/srpr/logo11w.png";
//}

var errorURL = "https://www.google.com/images/srpr/logo11w.png";

$('[data-original]').each(function() {
  var $this = $(this),
      src = $this.attr('data-original');
      
  var img = new Image();
  img.onload = function() {
    $this.attr('src', src);
  }
  img.onerror = function() {
    $this.attr('src', errorURL);
  }
  img.src = src;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Error:
<img data-original="http://pacehold.it/600x450" class="img-responsive lazy" alt=""> <br />
OK:
<img data-original="https://www.w3schools.com/html/pic_mountain.jpg" class="img-responsive lazy" alt="">