在Jquery中调用公共插件方法时如何传递对象

时间:2013-06-08 21:55:31

标签: jquery plugins

我正在构建一个jQuery插件,里面会有几个公共方法。这就是它现在的样子。

(function ($) {
    $.fn.ajDialogue = function (options) {

        var opts = $.extend({}, $.fn.ajDialogue.defaults, options);

        return this.each(function () {
            var $this = $(this);
            $.fn.ajDialogue.show();
        });

    };

    $.fn.ajDialogue.show = function () {
        // code
    };

    $.fn.ajDialogue.destroy = function () {
        console.log(this);
        // 'this' is this plugin
    };

    $.fn.ajDialogue.defaults = {
        width: 100,
        height: 100,
        onShow: function () { },
        onDestroy: function () { }
    };


})(jQuery);

我正在声明并运行这样的插件,效果很好。

var $myPluginElement = $('body').ajDialogue();

但是当我这样做时

$myPluginElement.ajDialogue.destroy();

我没有将$ myPluginElement传递给public方法。正如我评论的那样,控制台只输出'this'作为整个插件,而不是$ myPluginElement。喜欢这个

function (options) {

        var opts = $.extend({}, $.fn.ajDialogue.defaults, options);

        return this.each(function () {
            var $this = $(this);
            $.fn.ajDialogue.show();
        });
} 

我是否认为错误,我需要做些什么才能拥有能够发送元素的公共方法?

谢谢!

2 个答案:

答案 0 :(得分:1)

我不是一个jQuery插件专业版或者其他什么......无论如何我会让这样的事情发生如此

<span id="test"></span>


(function ($) {
$.fn.ajDialogue = function (options) {

    var opts = $.extend({}, $.fn.ajDialogue.defaults, options);

    return this.each(function () {
        var $this = $(this);
        $.fn.ajDialogue.show();
    });

};

$.fn.ajDialogue.show = function () {
    // code
};

$.fn.ajDialogue.destroy = function (element) {
    alert(element);
    // 'this' is this plugin
};

$.fn.ajDialogue.defaults = {
    width: 100,
    height: 100,
    onShow: function () { },
    onDestroy: function () { }
};


})(jQuery);


$(window).ajDialogue.destroy($('#test'));

工作js小提琴示例here

答案 1 :(得分:1)

似乎是一种奇怪的做事方式,我通常做这样的事情:

(function ($) {
    $.fn.ajDialogue = function (options) {
        var defaults = {
                width: 100,
                height: 100,
                onShow: function () { },
                onDestroy: function () { }
            },
            self = this,
            opts = $.extend(defaults, options);

        this.show = function() {
            console.log(this);
        }
        this.destroy = function() {
            console.log('destroy');
        }

        return this.each(function () {
            self.show()
        });
    };
})(jQuery);

var $myPluginElement = $('body').ajDialogue();

$myPluginElement.show();

FIDDLE

相关问题