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

      

     

      

      

  • 相关阅读:
    JavaScript字面量
    JavaScript一元运算符、二元运算符和三元运算符
    JavaScript变量声明与变量声明提前
    JavaScript作用域链
    JavaScript变量污染
    语法糖
    JavaScript包装对象
    JavaScript全局变量与局部变量
    JavaScript标识符
    JS函数命名规范
  • 原文地址:https://www.cnblogs.com/dfghjkl/p/5329814.html
Copyright © 2011-2022 走看看