插件是對(duì)具體業(yè)務(wù)邏輯的一個(gè)針對(duì)性封裝,在代碼層面,就是一個(gè)函數(shù)或者方法,按需調(diào)用。jQuery里提供了兩種兩種類型的插件實(shí)現(xiàn)方法。一個(gè)是擴(kuò)展jQuery類方法,一個(gè)是擴(kuò)展jQuery實(shí)例方法。
## jQuery類方法的擴(kuò)展(jQuery.extend())
類方法是就jQuery自身的方法,如果foo是jQuery自身方法,就可以這樣調(diào)用$.foo();實(shí)現(xiàn)起來也超級(jí)簡(jiǎn)單的,就跟平常給一個(gè)對(duì)象添加方法一樣:
```js
jQuery.foo = function(){
console.log("我是jQuery類方法foo");
}
jQuery.foo();
```
在jQuery里,專門提供了用于擴(kuò)展類方法的寫法jQuery.extend(),可以一次擴(kuò)展多個(gè)方法,用法如下:
```js
$.extend({
fn1: function () {},
fn2: function () {},
});
$.fn1();
$.fn2();
$.fn3(); //報(bào)錯(cuò)
```
## jQuery實(shí)例方法的擴(kuò)展(jQuery.fn.extend())
實(shí)例方法就是jQuery實(shí)例對(duì)象訪問的方法,我們知道,按照面向?qū)ο髮?duì)象設(shè)計(jì)思想,實(shí)例訪問的方法通常是放到原型對(duì)象prototype上的。jQuery提供的用于擴(kuò)展實(shí)例方法的寫法是$.fn.extend(),這就意味著有這樣一個(gè)等式關(guān)系成立:
```js
jQuery.prototype === $.fn //true
```
所以我們只需把擴(kuò)展的方法寫到$.fn.extend()的小括號(hào)里即可:
```js
$.fn.extend({
fn1:function(){},
fn2:function(){}
})
//jquery實(shí)例對(duì)象$("div")訪問情況
$("div").fn1();
$("div").fn2();
$("div").fn3(); //報(bào)錯(cuò)
```
對(duì)jQuery實(shí)例方法的擴(kuò)展,有一個(gè)需要我們注意的地方,就是參數(shù)。大家知道,參數(shù)的設(shè)計(jì)分為三種情況,那就是不帶參數(shù),必傳參數(shù),可選參數(shù)。接下來我們以一個(gè)高亮顯示的例子給大家演示下。
```text
<!-- html結(jié)構(gòu) -->
<div>高亮顯示</div>
```
不帶參數(shù)
```js
$.fn.extend({
highLight() {
//讓實(shí)例對(duì)象的背景顏色和文字顏色發(fā)生改變
//highLight是一個(gè)原型方法,this表示的是實(shí)例
this.css({ "background-color": "yellow", color: "red" });
return this;//形成鏈?zhǔn)秸{(diào)用
},
});
$("div").highLight().width("500px");//黃底紅字寬500
```
必傳參數(shù)
```js
$.fn.extend({
highLight(bgColor, color) {
this.css({ "background-color": bgColor, color });
return this;
},
});
$("div").highLight("blue", "white").width("500px");//藍(lán)底白字寬500
```
可選參數(shù),意思就是不傳就用默認(rèn)的,傳參就用自定義的,
```js
//多個(gè)參數(shù)逐一列出
$.fn.extend({
highLight(bgColor = "yellow", color = "red") {
this.css({ "background-color": bgColor, color });
return this;
},
});
$("div").highLight(); //黃底紅字
$("div").highLight("blue"); //藍(lán)底紅字
$("div").highLight("blue", "white"); //藍(lán)底白字
//一個(gè)參數(shù)對(duì)象
$.fn.extend({
highLight(opts) {
let defaults = { bgColor: "yellow", color: "red" }; //默認(rèn)值
//取到實(shí)際的值 options
let options = $.extend({}, defaults, opts);//將一個(gè)或多個(gè)源對(duì)象復(fù)制給目標(biāo)對(duì)象
this.css({
"background-color": options.bgColor,
color: options.color,
});
return this;
},
});
$("div").highLight();//黃底紅字
$("div").highLight({ bgColor: "blue"});//藍(lán)底紅字
$("div").highLight({ bgColor: "blue", color: "white" });//藍(lán)底白字
```
怎么樣,是不是炒雞簡(jiǎn)單~~~
更多關(guān)于web培訓(xùn)的問題,歡迎咨詢千鋒教育在線名師。千鋒教育擁有多年IT培訓(xùn)服務(wù)經(jīng)驗(yàn),采用全程面授高品質(zhì)、高體驗(yàn)培養(yǎng)模式,擁有國內(nèi)一體化教學(xué)管理及學(xué)員服務(wù),助力更多學(xué)員實(shí)現(xiàn)高薪夢(mèng)想。