如何为自定义jQuery插件创建函数

时间:2014-08-13 09:44:10

标签: javascript jquery

我正在使用jquery.boilerplate.js创建一个简单的自定义jQuery插件。现在我想创建一个名为

的函数
var div1 = $("#div1").changeBackgroundColor({
  color: $('#colorCode').val().trim()
});
div1.getColor();

如何在jquery插件中定义getColor()方法。

自定义插件

;(function($, window, document, undefined) {
var pluginName = "changeBackgroundColor", defaults = {
    color : "black"
};

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() {
        console.log("Hello");
    }
});

$.fn[pluginName] = function(options) {
    this.each(function() {
        if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this,
                    options));
            }
        console.log(options);
        if(options===undefined){
            $(this).css("background-color", defaults.color);
        } else{ 
            $(this).css("background-color", options.color);
        }
    });
    return this;
};

})(jQuery, window, document);

谢谢.... :)

3 个答案:

答案 0 :(得分:1)

你有点错过了插件和OOP的全部内容。

  1. $.fn[pluginName] - 应该扮演基础架构角色并将实际工作委托给Plugin实例。
  2. Plugin实例应该使用element执行实际工作。
  3. 如果要调用Plugin个实例上的方法,可以$.fn[pluginName]处理options为字符串时的特殊情况。 $(selector).changeBackgroundColor('methodToBeCalled' /*rest arguments*/)
  4. Demo

    ;(function($, window, document, undefined) {
    var pluginName = "changeBackgroundColor", 
        defaults = {
            color : "black"
        },
        //methods to be called via $().changeBackgroundColor(name)
        publicMethods = { 
            getColor: function() {
                return this.settings.color;        
            },
            setColor: function(color) {
                this.settings.color = color;
                this.element.css('background-color', color);            
            }
        },
        privateMethods = { //internal methods
            init : function() {
                console.log('init');
                this.setColor(this.getColor());            
            }
    };
    
    function Plugin(element, options) {
        this.element = $(element);
        this.settings = $.extend({}, defaults, options);
    
        this.init();
    }
    
    //copy private and public methods
    $.extend(Plugin.prototype, privateMethods, publicMethods); 
    
    $.fn[pluginName] = function(options) {
        var out = [],
            args = [].slice.call(arguments, 1);
        this.each(function() {
            var plugin = $.data(this, pluginName), 
                method;
    
            if (!plugin) { //create new plugin  
                plugin = new Plugin(this, options)                  
                return $.data(this, pluginName, plugin);            
            }
            //handle method calls
            if(typeof options === 'string' && publicMethods[options]) { 
                out.push(plugin[options].apply(plugin, args));
            }        
        });
        return out.length ? (out.length === 1 ? out[0] : out) : this;
    };
    
    })(jQuery, window, document);
    

    用法

    $('#a').changeBackgroundColor();
    $('#b').changeBackgroundColor({color: 'navy'});
    $('#c').changeBackgroundColor({color: 'green'});
    console.log($('#b').changeBackgroundColor('getColor'));
    console.log($('#b, #c').changeBackgroundColor('getColor'));
    
    $('#a').changeBackgroundColor('setColor', 'red');
    console.log($('#a').changeBackgroundColor('getColor'));
    

答案 1 :(得分:0)

像这样定义你的方法

$.fn.getColor = function() { 
     alert('getColor called'); 
}

<强> Basic Custom Plugin

答案 2 :(得分:0)

像这样创建你的插件:

$.fn.highlight = function(){
  this.css("background","yellow").css("color","black");
  return this;
}

$(".highlight").highlight().fadeIn();
在上面的例子中,我创建了一个简单的jQuery插件,它将突出显示一个元素。我认为你应该检查这个http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/