Jquery plugins jquery插件创建问题

Jquery plugins jquery插件创建问题,jquery-plugins,jquery,Jquery Plugins,Jquery,我创建了一个包含以下代码的插件: var myplugin = { init: function(options) { $.myplugin.settings = $.extend({}, $.myplugin.defaults, options); }, method1: function(par1) { ..... }, method2: function(par1) { ..... } };

我创建了一个包含以下代码的插件:

var myplugin = {
    init: function(options) {
         $.myplugin.settings = $.extend({}, $.myplugin.defaults, options);
    },
    method1: function(par1) {
        .....
    },
    method2: function(par1) {
        .....
    }
};
$.myplugin = function(method){
     if ( myplugin[method] ) {
    return myplugin[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
     } else if (typeof method === 'object' || !method) {
        return myplugin.init.apply(this, arguments);
     } else {
    $.error( 'Method "' +  method + '" does not exist in myplugin!');
     }
};
$.myplugin.defaults = {
     option1: 'test',
     option2: '',
     option3: ''
};
$.myplugin.settings = {};
$.myplugin();
这很好,但问题是,当我尝试设置多个选项并尝试在之后返回其值时,它会给出空值;设置一个选项效果很好。例如。 如果更改第一个组合框值,我将其称为: $.myplugin({option1:'first test'}); 它可以工作,但当我尝试在第二个组合框中调用另一个组合框时,它不会保存该选项,而是将其重置为空


是否有任何修复方法?

我将重新组织插件以使用此结构:

var methods = {
    settings: {
        foo: "foo",
        bar: "bar"
    },
    init: function(options) {
        this.settings = $.extend({}, this.settings, options);
    },
    method1: function(par1) {
        alert(this.settings.foo);
    },
    method2: function(par1) {
        alert(this.settings.bar);
    }
};

function MyPlugin(options) {
    this.init(options);
    return this;
}
$.extend(MyPlugin.prototype, methods);
$.myPlugin = function(options) {
    return new MyPlugin(options);
}

/* usage */

// without parameters
var obj1 = $.myPlugin();
// with parameters
var obj2 = $.myPlugin({foo: "foobar"});
// each has it's own settings
obj1.method1();
obj2.method1();
演示:


实际上,
$.myPlugin
只是创建并返回myPlugin类的一个新实例。你可以完全摆脱它,使用新的myPlugin(选项)。

你的插件不是用来处理多个元素的,你应该使用
$.fn.myPlugin
而不是
$。myPlugin
实际上我不想将它用作带有元素的jquery原型。我只想将它作为一个常规功能来执行不同的操作。您不能将
设置存储在存储它的位置,否则每次使用插件时,它都会覆盖以前设置的任何设置。它们必须存储在与其影响的内容相关的位置,通常存储在元素的数据对象上<代码>$(元素)。数据(“mypluginsettings”,设置)
非常有用的回复。我想知道,如果我不想将此数据对象与任何元素一起使用,它是否可供全局使用?您需要为您创建的插件的每个实例存储不同的设置,并且这些设置需要保留在插件返回的某种对象中。然后,您将使用返回的对象对该实例执行操作。最后一个问题。在以下示例中:var myplugin={init:function(options){$.myplugin.settings=$.extend({},$.myplugin.defaults,options);},method1:function(par1){….},method2:function(par1){….};如何从method2调用method1,反之亦然?使用您的方法还是我的方法?在我的系统中,它将是
this.method1()
this.method2()
,在你的系统中,它将是
$.myplugin.method1()
$.myplugin.method2
凯文非常感谢,它解决了我的问题。:)同时,你能给我推荐一本书吗?在这本书中,我可以更详细地了解jquery中这些类型的对象创建。