jQuery插件覆盖参数

jQuery plugin override parameters

本文关键字:参数 覆盖 插件 jQuery      更新时间:2023-09-26

在这个插件中,想要用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/