Javascript html中图像标记的alt属性

Javascript html中图像标记的alt属性,javascript,html,image,alt,Javascript,Html,Image,Alt,情景: <img src="filepath" alt="image not found"> 这将确保如果在路径中找不到文件,则将加载文本 问题: 可以加载图像而不是其他文本吗??是否有任何标记可以满足我的目的?是否有任何自定义javascript函数可以在#alt tag中提供???您可以检查图像是否加载到javascript中: var img = document.getElementById('image'); if ( img.complete &&

情景:

 <img src="filepath" alt="image not found">

这将确保如果在路径中找不到文件,则将加载文本

问题:
可以加载图像而不是其他文本吗??是否有任何标记可以满足我的目的?是否有任何自定义javascript函数可以在#alt tag中提供???

您可以检查图像是否加载到javascript中:

var img = document.getElementById('image');
if ( img.complete && img.naturalWidth == 0 ) {
  // some error, load alternate image:
  img.src = "path to alternative img";
}

编辑:完整的解决方案(使用@JoDev答案中的
onerror
)是:

<script>
function validate (img) {
  // Clear the callback to avoid infinite loop in case
  // new image path would be also invalid.
  img.onerror = null;

  if ( img.complete && img.naturalWidth == 0 ) {
    // some error, load alternate image:
    img.src = "http://example.com/valid_path.png";
  }
}
</script>

<img onerror="javascript:validate(this);" 
     src="http://example.com/some_invalid_path.png"/>

功能验证(img){
//清除回调以避免出现无限循环
//新映像路径也将无效。
img.onerror=null;
if(img.complete&&img.naturalWidth==0){
//出现一些错误,请加载备用图像:
img.src=”http://example.com/valid_path.png";
}
}

有一个特殊的活动可以让您进行此操作。它是:

<img src="" onerror="this.src='path/to/default'" />

请参考下面的代码

在onerror函数中,添加要加载的src路径。如果src为,则加载图像



无法加载图像。(您有什么保证可以找到并加载该图像?然后是否要为alt图像设置alt图像?等等)请注意,
alt
属性基本上是一个可访问性功能。在无法显示图像的环境中(例如屏幕阅读器),另一个图像不是适当的替代品。我建议您将该属性用于预期目的(如果适用,请提供图片的简要说明,其中“未找到图像”不存在),并找到另一种方法来检测缺少的图片。请参阅“是否可以使用此属性..如果可以,如何在内部html中使用此属性??