从插件的辅助功能访问jQuery对象

时间:2013-06-24 16:45:12

标签: javascript jquery plugins jquery-plugins

我正在编写一个jQuery插件,该插件具有辅助功能(请参阅jQuery support)。我希望能够循环遍历jQuery对象包含的元素,以便为每个元素执行某些操作。但是,我无法看到如何访问原始对象,因为在辅助函数的范围内,this显然是指插件对象。

有没有办法访问原始元素,或者我将不得不开始考虑替代(jQuery UI -esque)技术?

代码看起来像这样:

(function ($) {
    'use strict';
    var
        myNewPlugin,
        mySecondaryFunction;

    mySecondaryFunction = function () {
        // the secondary function

        // `this` refers to myNewPlugin
    };

    myNewPlugin = (function () {
        var closedPrivateVariables;

        return function () {
            // the function called from the jQuery object

            return this;
        };
    }());

    myNewPlugin.mySecondaryFunction;

    $.fn.myNewPlugin = myNewPlugin;
}(jQuery));

不重复(听起来相似但不一样的问题)

1 个答案:

答案 0 :(得分:4)

标准插件模式是这样的:

(function ($) {
    $.fn.myPlugin = function (options) {
        var settings = {
            // settings
        };
        return this.each(function (i, elem) {
            //do stuff
        });
    };
})(jQuery);

要为辅助函数扩展它并维护对所选jQuery对象的引用,只需在.each()迭代器中捕获对它的引用:

(function ($) {
    $.fn.myPlugin = function (options) {
        var settings = {
            // settings
        },
        self = null,
        selectedDOMElements = [],
        mySecondaryFunction = function () {
            var i = 0;
            //do more stuff
            self.css('display', 'inline-block'); //original jQuery object
            for (i = 0; i , selectedDOMElements.length; i += 1) {
                $(selectedDOMElements[i]).css('color', '#F00'); //individual child elements of the original jQuery object
            }
        };
        self = this; //store original jQuery object
        return this.each(function (i, elem) {
            selectedDOMElements.push(elem); //store individual child elements of the original jQuery object
            //do stuff
        });
    };
})(jQuery);

混合搭配去做你想做的事。

<强>更新

请改为尝试:

(function ($) {
    var self;
    $.fn.myPlugin = function (options) {
        var settings = {
            // settings
        };
        self = this; //store original jQuery object
        return self.each(function (i, elem) {
            //do stuff
        });
    };
    $.fn.myPlugin.mySecondaryFunction = function mySecondaryFunction(options) {
        var settings = {
            // settings
        };
        return self.each(function (i, elem) { //apply to original jQuery object
            //do stuff
        });
    };
})(jQuery);

//call like this
$(selector).myPlugin();
$(selector).myPlugin.mySecondaryFunction();

示例小提琴:http://jsfiddle.net/bv7PG/