Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to avoid getting:

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the error event:

var im = document.getElementById('imageID'); // or select based on classes
im.onerror = function(){
  // image not found or change src like this as default image:

   im.src = 'new path';
};

Inline Version:

<img src="whatever" onError="this.src = 'new default path'" />

Or

<img src="whatever" onError="doSomething();" />

<img> tag supports these events:

  • abort (onAbort)
  • error (onError)
  • load (onLoad)

More Information:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...