jQuery如何使用error()方法?介绍和示例

2021年3月25日12:15:46 发表评论 855 次浏览

error()方法当元素遇到错误(该元素未正确加载)时, 使用jQuery中的。的error()方法附加一个函数, 以在发生错误事件或触发错误事件时运行。

语法如下:

  • 错误事件中的功能添加:
    $(selector).error(function)
  • 触发某些选定元素的错误事件:
    $(selector).error()

参数:

  • 功能:此参数是可选的, 它指定发生错误事件时要运行的功能。

示例1:

<!DOCTYPE html>
< html >
  
< head >
     < title >error() method</ title >
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
   </ script >
    
   < script >
         $(document).ready(function() {
             $("img").error(function() {
                 $("img").replaceWith(
                   "< h3 >Error occurs</ h3 >");
             });
         });
     </ script >
</ head >
  
< body >
     < center >
  
         < h1 >Welcome to lsbin!.</ h1 >
         < div style = "background-color:yellow;" >
         < img src =
"https://media.lsbin.org/wp-content/uploads/20190220214542/a13.png" >
       </ div >
         < div style = "background-color:green" >
  
         < h3 > The image will be replaced with specified
        text if the image above encounters an error.</ h3 >
  
         </ div >
     </ center >
  
</ body >
  
</ html >

输出如下:

jQuery | error()方法1

示例2:

<!DOCTYPE html>
< html >
  
< head >
     < title >error() method</ title >
     < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" >
   </ script >
     < script >
         $(document).ready(function() {
             $("img").error(function() {
               $("img").replaceWith(
                "< h3 >Error </ h3 >");
             });
         });
     </ script >
</ head >
  
< body >
     < center >
         < div style = "background-color:green" >
             < h1 >Welcome to lsbin!.
           </ h1 >
         </ div >
         < img src =
"https://media.lsbin.org/wp-content/uploads/20190220220257/a22.png" 
              width = "284" 
              height = "113" >
  
       < h3 >Image is replaced with a specified 
         text, if error occur in loading.</ h3 >
  
     </ center >
  
</ body >
  
</ html >

输出如下:

jQuery | error()方法2

注意:此方法已在jQuery 3.0版中删除.


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: