加载图片失败,怎样替换为默认图片

img元素加载图片失败,则变成一个小图标,让页面变得难看。此时如何替换为默认图片?

onerror属性

img元素自带onerror属性,加载失败时,触发error事件

<img src="http://yongqing.is-programmer.com/posts/image.gif" onerror='this.src="http://yongqing.is-programmer.com/posts/default.gif" />

jquery.error函数

jquery提供对应的事件处理函数

$('img').error(function(){
    $(this).attr('src',"default.gif");
})

jquery.one函数

使用上面两种方法,假如默认图片也加载失败,则变成死循环. 此时可使用one()绑定事件

$("img").one("error", function(e){
     $(this).attr("src", "default.gif");
});

 另外error事件,不支持冒泡,jquery.delegate函数捕捉不到error事件。

事例

$.ajax({
	type : "post",
	url : "<%=request.getContextPath()%>/ce/articledetail/main.do?method=getContent",
	data : {zbGuid:zbGuid},
	dataType : "html", 
	success : function(result) {
        $("#cont").html("<pre>"+result+"</pre>");		
        $("img").one("error", function(e){
		$(this).css({
		       'display':'none'//图片加载失败让其隐藏
			});
				     
		   });

  

 

  

  

原文地址:https://www.cnblogs.com/dfghjkl/p/5329814.html