jQuery/JavaScript to replace broken images

后端 未结 30 2609
我寻月下人不归
我寻月下人不归 2020-11-21 05:50

I have a web page that includes a bunch of images. Sometimes the image isn\'t available, so a broken image is displayed in the client\'s browser.

How do I use jQuery

30条回答
  •  我寻月下人不归
    2020-11-21 06:02

    While the OP was looking to replace the SRC, I'm sure many people hitting this question may only wish to hide the broken image, in which case this simple solution worked great for me.

    Using Inline JavaScript:

    Using External JavaScript:

    var images = document.querySelectorAll('img');
    
    for (var i = 0; i < images.length; i++) {
      images[i].onerror = function() {
        this.style.display='none';
      }
    }

    Using Modern External JavaScript:

    document.querySelectorAll('img').forEach((img) => {
      img.onerror = function() {
        this.style.display = 'none';
      }
    });

    See browser support for NodeList.forEach and arrow functions.

提交回复
热议问题