的jQuery插件模板做了一些事情:
樣板設置$
跡象jQuery來避免插件衝突(如樣機也使用$
如jQuery,那麼你如何確保你的插件使用jQuery和沒有別的東西,你通過jQuery的成Immediately Invoked Function Expression像這樣):
(function($) {
$.fn.yourPlugin = function() {
// Do stuff!
};
})(jQuery); // pass jQuery so the $ is jQuery and not something else in the function
但是,這並不能解決所有問題,因爲undefined
ECMAScript中3可能不會undefined
(即,它是可變的,它可以由oth修改呃腳本),所以我們增加一個參數:
(function($, undefined) {
$.fn.yourPlugin = function() {
// Do stuff!
};
})(jQuery); // note that we're not passing any value to make it truly undefined
樣板也通過window
和document
局部變量,使他們得到解決快一點,而且還增添了一些代碼,以便插件可以像其他jQuery對象一樣鏈接。現在我們結束了樣板代碼:
;(function ($, window, document, undefined) {
var pluginName = "highlighter";
var defaults = {
};
function Plugin (element, options) {
this.element = element;
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function() {
}
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ pluginName ] = function (options) {
this.each(function() {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
// chain jQuery functions
return this;
};
})(jQuery, window, document);
現在讓我們來探索如何突出顯示div並更改字體。首先,你可以用一些屬性擴展默認設置:
// Here we create the defaults:
var defaults = {
bgColor: 'yellow',
font: 'normal small-caps normal 16px/1.4 Georgia'
};
在插件的包裝,當你的插件實例化時,也稱init()
功能:
// "options" parameter may contain the user's values to override defaults
$.fn[ pluginName ] = function (options) {
// for each selected element
this.each(function() {
// ...
// When "new Plugin()" -> init() is called in the function, see "function Plugin()"
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
}
樣板也做一個其他重要的是:它在this.settings
而不是this.defaults
存儲用戶的設置,以便插件的默認設置不會被用戶的自定義設置覆蓋。
的new Plugin()
調用init()
功能,我們可以工作了魔法。要訪問默認或自定義設置,我們只需要訪問this.settings
:
init: function() {
// Set the highlight and font.
$(this.element).css({
'background-color': this.settings.bgColor,
'font': this.settings.font
});
}
見小提琴here。
你說的亮點是什麼意思?像背景顏色?或者像jQuery UI的動畫高光? – arao6 2014-11-05 05:56:51
是的插件允許我只指定背景顏色和自定義字體。如果不是可以在插件中指定默認值 – CuriousDev 2014-11-05 06:08:57
下面是一個示例小提琴:http://jsfiddle.net/5h68swxq/2/基本上,默認屬性在'this._defaults = defaults'的構造函數中設置。但是,settings對象在'this.settings = $ .extend({,defaults,options);'擴展了默認對象;'以便不覆蓋其他元素的默認設置。在初始化時,您使用jQuery的'css'函數應用這些設置。 – arao6 2014-11-05 06:20:11