[英]jQuery plugin override parameters
在此插件中,要使用jQuery更改背景顏色。 默認的背景顏色是紅色,但是當我嘗試覆蓋參數然后不起作用時,在這里我試圖將背景顏色設置為綠色。 但不起作用,仍然是紅色
這是插件文件上的代碼
(function($){
if(!$.fn){
$.fn = new Object();
};
$.fn.myBgcolor = function(el, options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
// Add a reverse reference to the DOM object
base.$el.data("fn.myBgcolor", base);
base.init = function(){
base.options = $.extend({},$.fn.myBgcolor.defaultOptions, options);
// Put your initialization code here
};
// Sample Function, Uncomment to use
base.BGcolor = function(paramaters){
base.css("background-color", base.options.bgColor);
};
// Run initializer
base.init();
base.BGcolor();
};
$.fn.myBgcolor.defaultOptions = {
bgColor: "red"
};
$.fn.fn_myBgcolor = function(options){
return this.each(function(){
(new $.fn.myBgcolor(this, options));
});
};
// This function breaks the chain, but returns
// the fn.myBgcolor if it has been attached to the object.
$.fn.getfn_myBgcolor = function(){
this.data("fn.myBgcolor");
};
})(jQuery);
這是HTML文件上的代碼
<p class="ele">dfdfg</p>
$(".ele").myBgcolor({
bgColor: "green"
});
我不確定您要通過以下兩行嘗試實現什么,因為this
已經指向jQuery對象。
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
這里的第一個錯誤是多余的參數el
,它指向選項而不是元素,因此必須將其刪除:
$.fn.myBgcolor = function(/* el, */ options)
然后您的構造函數應如下所示:
$.fn.myBgcolor = function(options){
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Add a reverse reference to the DOM object
base.data("fn.myBgcolor", base);
base.init = function(){
base.options = $.extend({},$.fn.myBgcolor.defaultOptions, options);
// Put your initialization code here
};
// Sample Function, Uncomment to use
base.BGcolor = function(paramaters){
base.css("background-color", base.options.bgColor);
};
// Run initializer
base.init();
base.BGcolor();
};
在此處查看示例http://jsfiddle.net/7Rrs3/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.