在这个插件中想用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"
});
答案 0 :(得分:1)
由于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/