Created
December 18, 2013 06:55
-
-
Save caok/8018311 to your computer and use it in GitHub Desktop.
图片不存在时,显示一个默认的图片
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<img src="abc.JPG" onerror="this.src='default.JPG'" /> | |
或者 | |
<script type="text/javascript"> | |
t = document.getElementsByClassName("defaultImg"); | |
for(i = 0; i < t.length; i++){ | |
t.item(i).onerror = function(){ | |
this.src = "test.gif" | |
} | |
} | |
</script> | |
//采用 className 是为了更好的适应页面,不是每个img我们都要这样做的,甚至不同地方的img | |
//我们要显示不同的默认图片。(采用img同样做法)。 | |
//采用id则是犯了错误,id 导致只会拿到第一个id相符的。 | |
//此代码经过测试在 非IE 的browser上正常工作。 | |
//为了兼容IE,请使用以下代码: | |
<script type="text/javascript"> | |
t = document.getElementsByTagName("img"); | |
for(i = 0; i < t.length; i++){ | |
t.item(i).onerror = function(){ | |
if(this.id =="defaultImg"){ | |
this.src = "test.gif"; | |
this.onerror = null; | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment