jQuery中的error()和ajaxError()事件有什么区别?

jQueryerror()方法

error()当元素遇到错误时,该方法将触发事件。jQuery 1.8中不推荐使用此方法。

示例

您可以尝试运行以下代码以了解如何error()在jQuery中使用方法-

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("img").error(function(){
        $("img").replaceWith("<p>Image isn't loading</p>");
    });
    $("button").click(function(){
        $("img").error();
    });
});
</script>
</head>
<body>

<img src="/videotutorials/images/tutorial_library_home.jpg" alt="Video Tutorial" width="300" height="200"><br>

<button>Error event</button>

</body>
</html>

jQueryajaxError()方法

只要AJAX请求失败,ajaxError(callback)方法就会附加一个要执行的函数。这是一个Ajax事件。

示例

您可以尝试运行以下代码以了解如何ajaxError()在jQuery中使用方法-

<html>

   <head>
      <title>jQuery ajaxError() method</title>
      <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
           
            $("#driver").click(function(event){
               /* Assume result.text does not exist. */
               $('#stage1').load('/jquery/result.text');
            });

            $(document).ajaxError(function(event, request, settings ){
               $("#stage2").html("<h1>Error in loading page.</h1>");
            });
               
         });
      </script>
   </head>

   <body>
   
      <p>Click on the button to load result.text file:</p>
       
      <div id = "stage1" style = "background-color:blue;">
         STAGE - 1
      </div>
       
      <div id = "stage2" style = "background-color:blue;">
         STAGE - 2
      </div>
       
      <input type = "button" id = "driver" value = "Load Data" />
       
   </body>
   
</html>