see if src of img exists

北城余情 提交于 2020-01-09 12:41:13

问题


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:


回答1:


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:

  • JavaScript Events
  • jQuery's error



回答2:


you can make a previous ajax call (with head method) and see the server return code or you can use onerror event to change url or make it hidden, e.g.

<img src="notexist.jpg" onerror="this.style.visibility = 'hidden'">

(I've used inline attribute just to explain the idea)




回答3:


If you create the src dynamically with javascript you can use this:

var obj = new Image();
    obj.src = "http://www.javatpoint.com/images/javascript/javascript_logo.png";

if (obj.complete) {
    alert('worked');
} else {
    alert('doesnt work');
}



回答4:


You're approaching this the wrong way.
When you generate your links with the server side script, check it there whether the file exists or not (by using file_exists() in PHP for example).

You shouldn't rely on JavaScript when you can do it in the server side, as JavaScript can be altered and disabled.

Ask yourself how are you generating the src= attributes, and check there whether the file exists or not, and provide an alternative.



来源:https://stackoverflow.com/questions/9022427/see-if-src-of-img-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!