在做项目时遇到一个问题,当图片返回失败时,例如404的情况,不能正常的显示,刚开始是用vue.js做的,部分代码如下
<dt> <img v-bind:src="getHeadPic(user.headPic)" ?alt=""></dt>
methods:{ ???????getHeadPic:function(headPic){ ???????if(headPic != null && headPic != undefined && headPic != ‘‘){ ???????????return headPic ; ???????} ???????????return "http://woxin2.jx139.com/cztx/images/ic_default_head.png"; ???????}
通过vue.js动态绑定的方法,返回默认的头像,这种情况只考虑到headPic 为 null 、undefined、 ”‘‘的这三种情况,而没有考虑到返回的地址为404的情况,通过上网查资料得知,
img自身就带有 onerror属性,可以监控到图片是否加载失败的情况,于是乎,将代码调整如下
<img v-bind:src="getHeadPic(user.headPic)" ?onerror="this.onerror=null; this.src=‘http://woxin2.jx139.com/cztx/images/ic_default_head.png‘">
至此,问题完美解决!
js当图片返回404时如何展示默认图片
原文地址:http://www.cnblogs.com/sjs355/p/8085960.html