jQuery/JavaScript to replace broken images

后端 未结 30 3147
我寻月下人不归
我寻月下人不归 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:07

    I created a fiddle to replace the broken image using "onerror" event. This may help you.

        //the placeholder image url
        var defaultUrl = "url('https://sadasd/image02.png')";
    
        $('div').each(function(index, item) {
          var currentUrl = $(item).css("background-image").replace(/^url\(['"](.+)['"]\)/, '$1');
          $('', {
            src: currentUrl
          }).on("error", function(e) {
            $this = $(this);
            $this.css({
              "background-image": defaultUrl
            })
            e.target.remove()
          }.bind(this))
        })
    

提交回复
热议问题