如何扩展jQuery的插件?

时间:2012-05-01 16:29:49

标签: jquery jquery-plugins

我正在为jQuery编写插件。我有扩展插件的问题。我编写了插件,例如:http://docs.jquery.com/Plugins/Authoring

请参阅以下示例代码:

(function($){
    var i18n    = {};
    var methods = {};
    $.fn.myPlugin = function(options){
        //...
   };
})(jQuery);

如何扩展属性i18n

我希望能够支持存储在单独文件中的国际化插件设置。我该怎么办?

4 个答案:

答案 0 :(得分:2)

例如:

// plugin definition
$.fn.hilight = function(options) {
  // Extend our default options with those provided.
  // Note that the first arg to extend is an empty object -
  // this is to keep from overriding our "defaults" object.
  var opts = $.extend({}, $.fn.hilight.defaults, options);
  // Our plugin implementation code goes here.
};
// plugin defaults - added as a property on our plugin function
$.fn.hilight.defaults = {
  foreground: 'red',
  background: 'yellow'
};

从这里http://www.learningjquery.com/2007/10/a-plugin-development-pattern

这是一个非常好的教程,可以开始使用

答案 1 :(得分:1)

jQuery插件通常会扩展这样的选项:

var i18nOpts = $.extend({}, i18n, options.i18n);

文档:http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options

这在插件本身内发生。

(function($){
    var i18n    = {};
    var methods = {};
    $.fn.myPlugin = function(options){
        var i18nOpts = $.extend({}, i18n, options.i18n);
   };
})(jQuery);

i18n只存在于该函数内部,为了扩展它,您现在可以将选项传递给插件。

$('#myDiv').myPlugin({
    i18n: {
        option1: "value",
        option2: "Value2"
    }
});

答案 2 :(得分:1)

下面是我自己使用的一个方便的模板..

(function($){

var MyClass = function (element, options){

   this.options = $.extend({}, options);

   this.someFunction = function (){...}  //Public members

   var otherFunction = function(){...}   //Private members

   $(element).data('pluginInstance', this);   

}


$.fn.myPlugin = function(options){

    var myClassInstace = new MyClass(this, options);

    //Do other things with the object.
}

})(jQuery);

答案 3 :(得分:0)

你可以通过jQuery的 $ .extend(objectA,objectB)方法来实现。我想你最好开始学习jquery插件开发。来自基本的hello world教程,例如此链接http://www.tectual.com.au/posts/3/How-To-Make-jQuery-Plugin-jQuery-Plugin-Hello-World-.html 或者在这里查看此帖子https://stackoverflow.com/a/11611732/1539647

相关问题