zoukankan      html  css  js  c++  java
  • 加载图片失败,怎样替换为默认图片

    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'//图片加载失败让其隐藏
    			});
    				     
    		   });
    

      

     

      

      

  • 相关阅读:
    java-多个数的和
    大道至简第二章
    大道至简第一章感悟上
    Tools
    LruCache
    Fragment
    科普指纹识别
    Python使用MySQL数据库
    Eclipse中添加PyDev插件
    UniversalAndroidImageLoader出现异常:ImageLoader: Unable to resolve host "https": No address associated with host
  • 原文地址:https://www.cnblogs.com/dfghjkl/p/5329814.html
Copyright © 2011-2022 走看看