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 >
输出如下:
示例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 3.0版中删除.