2

我正在尝试设置我的插件以接受内部的回调函数作为选项参数:

(function($) {

    $.fn.MyjQueryPlugin = function(options) {
        var defaults = {
            onEnd: function(e) {}
        };

        var settings = $.extend({}, defaults, options);

        return this.each(function() {
            // do stuff (complete() gets called here)

        });
    };

    function complete(e){
        settings.onEnd.call(this); // <- the error?
    }

})(jQuery);

但是我收到一个错误,即 call() 未定义。我的代码有什么问题?

好的,我将其更改为:

(function($) {

    $.fn.MyjQueryPlugin = function(options) {
        var defaults = {
            onEnd: function(e) {}
        };

        var settings = $.extend({}, defaults, options);

        var complete = function(e){
          settings.onEnd.call(this); // <- the error?
        }


        return this.each(function() {
            // do stuff (complete() gets called here)

        });
    };   

})(jQuery);

并且错误仍然存​​在...

4

3 回答 3

3

您试图settings在定义它的函数之外引用。您已将其范围限定settings为分配给的函数中的局部变量$.fn.MyjQueryPlugin,但随后您正在从不关闭该局部变量的函数中使用它。

可以complete为每个MyjQueryPlugin结束的调用创建一个新函数settings

(function($) {

    $.fn.MyjQueryPlugin = function(options) {
        var defaults = {
            onEnd: function(e) {}
        };

        var settings = $.extend({}, defaults, options);

        return this.each(function() {
            // do stuff (complete() gets called here)

        });

        // `complete` now closes over `settings`
        function complete(e){
            settings.onEnd.call(this); // <- the error?
        }
    };

})(jQuery);

...但当然这涉及到创建一个函数。也许这很好,取决于插件的作用。

或者,作为参数settings传入。complete

于 2011-04-26T08:24:28.480 回答
2

settings不在范围内complete()

于 2011-04-26T08:24:24.500 回答
1

变量设置超出了完整函数的范围。将完整的函数放在您定义设置的函数中。

$.fn.MyjQueryPlugin = function(options) {
    var defaults = {
        onEnd: function(e) {}
    };

    function complete(e){
        settings.onEnd.call(this); // <- the error?
    }

    var settings = $.extend({}, defaults, options);

    return this.each(function() {
        // do stuff (complete() gets called here)

    });
};
于 2011-04-26T08:31:06.220 回答