基本插件開(kāi)發(fā)
最簡(jiǎn)單的插件開(kāi)發(fā)就是對(duì)$.fn
添加新的成員函數(shù)丈攒。
$.fn.插件名 = function() {
//插件代碼
};
eg:
$.fn.greenify = function () {
this.css( "color", "green" );
};
$("a").greenify(); // Makes all links green.
注意:插件中的this
是jQuery對(duì)象的實(shí)例祷杈。
鏈?zhǔn)秸{(diào)用(Chaining)
jquery的一大特點(diǎn)是鏈?zhǔn)秸{(diào)用智袭。更改上面的插件方法:
$.fn.greenify = function () {
this.css( "color", "green" );
return this;
};
$( "a" ).greenify().addClass("greenified");
為防止$
符號(hào)同其他的沖突献烦,可以放到立即執(zhí)行函數(shù)中寫(xiě):
(function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
};
}( jQuery ));
另外曙求,** 盡量只使用一次$.fn
**
使用.each
如果需要針對(duì)每一個(gè)DOM元素進(jìn)行遍歷牌借、處理度气。則可以使用.each 方法:
$.fn.myNewPlugin = function () {
return this.each (function() {
//Do something to each element here
});
};
傳遞參數(shù)
(function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options );
// Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
};
}( jQuery ));
$( "div" ).greenify({
color: "orange"
});
//一般定義默認(rèn)的參數(shù)settings,然后使用$.extend({}, defaultOptions, options)來(lái)傳參膨报。
參數(shù)可修改
為了擴(kuò)展插件磷籍,有時(shí)候需要直接修改默認(rèn)參數(shù),來(lái)方便插件的調(diào)用现柠。
// Plugin definition.
$.fn.hilight = function( options ) {
// Extend our default options with those provided.
// Note that the first argument to extend is an empty
// object – this is to keep from overriding our "defaults" object.
var opts = $.extend( {}, $.fn.hilight.defaults, options );
// Our plugin implementation code goes here.
};
// Plugin defaults – added as a property on our plugin function.
$.fn.hilight.defaults = {
foreground: "red",
background: "yellow"
};
$.fn.hilight.defaults.foreground = "blue";
$( "#myDiv" ).hilight();
$( "#green" ).hilight({
foreground: "green"
});
方法可修改
另一種擴(kuò)展插件的方式是將插件的方法暴漏出去院领。
來(lái)自:微信公眾賬號(hào):myersguo
參考資料
https://learn.jquery.com/plugins/basic-plugin-creation/
http://javascript.ruanyifeng.com/jquery/plugin.html