標籤:
一、jQuery外掛程式開發的方法
jQuery外掛程式的編寫方法主要有兩種:
1、基於jQuery對象的外掛程式
2、基於jQuery類的外掛程式
二、基於jQuery類的外掛程式
1、什麼是jQuery類的外掛程式?
jQuery類方法其實就是jquery全域函數,即jquery對象的方法,實際上就是位於jquery命名空間的內建函式。這些函數有一個特徵就是不操作DOM元素,而是操作 Javascript非元素對象。直觀的理解就是給jquery類添加類方法,可以理解為添加靜態方法
2、給jQuery類添加方法。
//添加兩個全域函數 jQuery.foo = function(){ console.log("this is foo"); }; jQuery.foo();//this is foo jQuery.bar = function(){ console.log("this is bar") }; jQuery.bar();// this is bar
3、使用jQuery.extend()函數
jQuery自訂了jQuery.extend()與jQuery.fn.extend()方法,jQuery.extend()能夠建立工具函數或者選取器,jQuery.fn.extend()能夠建立jQuery對象命令。
//使用jQuery.extend()函數
jQuery.extend({ foo:function(){ console.log("this is foo"); }, bar:function(){ console.log("this is bar") }, }); $.foo();//this is foo $.bar();// this is bar
4、使用命名空間
雖然在jQuery命名空間中,禁止使用大量的Javascript函數名和變數名,但是仍然不可避免某些函數名或變數名與其他jQuery外掛程式衝突,因此習慣將一些方法封裝到另一個自訂的命名空間。
//使用命名空間 jQuery.myPlugin = { foo:function(){ console.log(‘this is foo‘); }, bar:function(){ console.log(‘this is bar‘); }, }; $.myPlugin.foo(); $.myPlugin.bar();
jQuery外掛程式開發(一):jQuery類方法