jQuery插件变量

Boj*_*les 1 variables jquery scope jquery-plugins

我有以下代码

(function($) {
    // carousel
    var Carousel = {
        settings: {
            itemsPerPage: 1,
            itemsPerTransition: 1,
            noOfRows: 1,
            pagination: true,
            nextPrevLinks: true,
            speed: 'normal',
            easing: 'swing',
            loop: false,
            auto: true,
            autoTime: 4000,

            maxHeight: 300,
            maxWidth: 500
        },
        init: function(el, options) 
        {
            if (!el.length) 
            { 
                return false; 
            }

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

            this.container = el;

            this.panelHeight = 0;
            this.panelWidth = 0;
            this.numPanels = 0;

            // Find biggest panel in set
            this.container.find(".tinycarousel > li > div").each(function() 
            {
                if($(this).outerHeight() > this.panelHeight)
                {
                    this.panelHeight = $(this).outerHeight();
                }

                if($(this).outerWidth() > this.panelWidth)
                {
                    this.panelWidth = $(this).outerWidth();
                }

                this.numPanels++;
            });

            alert(this.numPanels);
        },
        autoSwitch: function()
        {
            this.container.find(".tinycarousel").animate({marginLeft: -panelWidth});
        }
    };

    // bridge
    $.fn.tinycarousel = function(options) {
        return this.each(function() {
            var obj = Object.create(Carousel);
            obj.init($(this), options);
            $.data(this, 'carousel', obj);
        });
    };
})(jQuery);

我在这里遇到的问题是this.numPanels得到0的结果(我知道它应该是3).它在我使用之前有效,this.并且只是numPanels作为一个普通变量,但现在它没有.对不起,我无法提供更多信息,但我的问题是:如何在jQuery插件中创建变量'editable'.

编辑 我为任何困惑道歉 - 我只是不想发布一些愚蠢的代码并使其无法读取.请参阅上面的完整代码.

编辑2我觉得很糟糕...看看这个autoSwitch函数 - 这是我得到错误的地方:panelWidth is not defined这就是为什么我尝试使用this.

iiv*_*vel 9

this.numPanels ++在您的each()中调用的匿名函数的范围是本地的.如果您将初始声明替换为var numPanels = 0; 并在您的函数中访问它(或通过引用传入numPanels)您将获得预期的结果.

像这样做:

this.panelHeight = 0;
this.panelWidth = 0;
this.numPanels = 0;
var self = this; // reference to this
// Find biggest panel in set
this.container.find(".tinycarousel > li > div").each(function() {
    if($(this).outerHeight() > self.panelHeight) { // use self
        self.panelHeight = $(this).outerHeight();  // use self
    }

    if($(this).outerWidth() > self.panelWidth){    // use self
        self.panelWidth = $(this).outerWidth();    // use self
    }
    self.numPanels++; // use self
});
Run Code Online (Sandbox Code Playgroud)