0

我编写了以下 jQuery 插件:

(function($){
    $.fn.imageSlide = function(options){
      $(this).imageSlide.nextSlide();
      console.log("imageslide");
    };

    $.fn.imageSlide.nextSlide = function(){
      console.log("nextslide");
      $this = $(this);
    };

})(jQuery);

一些背景:

我想要一个图像滑块插件来交叉淡入淡出背景(出于性能原因,我不能使用Supersized插件)。我想向用户公开几个函数:imageSlide 插件“构造函数”和其他几个函数,例如imageSlide.nextSlideimageSlide.previousSlide,以使用户能够从插件外部执行这些操作。

imageSlide函数需要调用imageSlide.nextSlide function, 来滑入(或淡入)第一张图像。

问题:

似乎该行触发了函数$this = $(this);的无限递归。imageSlide.nextSlide

  • 为什么会这样?
  • 似乎这$.fn.imageSlide.nextSlide = function(){};不是在 jQuery 插件中公开另一个函数的正确方法。我该怎么做?
4

1 回答 1

0

我不确定究竟是什么导致了错误,但没有必要将所有静态方法都放在 jQuery 原型中。

尝试使用以下方式公开插件:

(function($) {

// The constructor of your plugin:
var imageSlide = function(elems, options) {
    this.elems = elems; // the targets from the jQuery selector
    this.options = options;
};

// the public inherited methods:
imageSlide.prototype = {
    nextSlide: function() {
        console.log('nextSlide called');
    }
};

// extending the jQuery prototype and returning only one instance:
$.fn.imageSlide = function(options) {
    return new imageSlide(this, options);
};

})(jQuery);

现在您可以调用插件,它的方法如下:

var myGallery = $('#gallery').imageSlide();
myGallery.nextSlide();
于 2010-07-25T20:05:46.843 回答