看看img的src是否存在 [英] see if src of img exists

查看:152
本文介绍了看看img的src是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我放置一个img标签时,我动态地创建了src属性。有没有一种方法来测试如果src(图像所在的路径)实际上存在于javascript中,以避免发生:

解决方案

您可以使用错误事件:

  var im = document.getElementById('imageID ); //或者根据类来选择
im.onerror = function(){
//找不到图像或将src改为默认图像:

im.src ='新路径;
};

内嵌版本:

 < img src =whateveronError =this.src ='new default path'/> 



 < img src =whateveronError =doSomething(); /> 






< img> 标签支持以下事件:




  • abort (onAbort )

  • 错误(onError)

  • 加载(onLoad)



更多信息

$ b

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:

解决方案

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:

这篇关于看看img的src是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆