jQuery/JavaScript to replace broken images

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

    Sometimes using the error event is not feasible, e.g. because you're trying to do something on a page that’s already loaded, such as when you’re running code via the console, a bookmarklet, or a script loaded asynchronously. In that case, checking that img.naturalWidth and img.naturalHeight are 0 seems to do the trick.

    For example, here's a snippet to reload all broken images from the console:

    $$("img").forEach(img => {
      if (!img.naturalWidth && !img.naturalHeight) {
        img.src = img.src;
      }
    }
    

提交回复
热议问题