jQuery.fn.extend() 方法
这个jQuery.fn.extend()方法是用来将一个对象的内容合并到jQuery原型上,以提供新的jQuery实例方法。
语法:
jQuery.fn.extend( object )
JavaScript
参数:该方法接受上面提到的和下面描述的单一参数。
- object:这个参数持有要合并到jQuery原型的对象。
返回值:它返回合并后的对象。
下面的例子说明了jQuery.fn.extend()方法的使用。
例子1:在这个例子中,jQuery.fn.extend()方法被用来添加两个方法到jQuery原型对象,然后使用其中一个。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery.fn.extend() method</title>
<script src=
"https://code.jquery.com/jquery-3.4.1.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color: green">
GeeksForGeeks
</h1>
<h3>jQuery.fn.extend() method</h3>
<p>
Add two methods to the jQuery prototype
object <br>and then use one of them.
</p>
<p><input type="radio" name="Geek_1"> Geek_1</p>
<p><input type="radio" name="Geek_2"> Geek_2</p>
<script>
jQuery.fn.extend({
Gfg1: function () {
return this.each(function () {
this.checked = true;
});
},
Gfg2: function () {
return this.each(function () {
this.checked = false;
});
}
});
// Use the newly created .Gfg1() method
$("input[type='radio']").Gfg1();
</script>
</body>
</html>
HTML
输出:
例子2:在这个例子中,jQuery.fn.extend()方法被用来合并更多的方法到jQuery原型对象。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery.fn.extend() method</title>
<script src=
"https://code.jquery.com/jquery-3.4.1.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color: green">
GeeksForGeeks
</h1>
<h3>jQuery.fn.extend() method</h3>
<p>
Add two methods to the jQuery prototype
object <br>and then use one of them.
</p>
<p><input type="checkbox" name="Geek_1"> Geek_1</p>
<p><input type="checkbox" name="Geek_2"> Geek_2</p>
<p><input type="checkbox" name="Geek_3"> Geek_3</p>
<p><input type="checkbox" name="Geek_4"> Geek_4</p>
<script>
jQuery.fn.extend({
Gfg1: function () {
return this.each(function () {
this.checked = true;
});
},
Gfg2: function () {
return this.each(function () {
this.checked = false;
});
}
});
// Use the newly created .Gfg1() method
$("input[type='checkbox']").Gfg1();
</script>
</body>
</html>
HTML
输出: