2010-07-25 112 views
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插件中公开另一个函数的正确方法。我该如何做到这一点?

回答

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(); 
+0

这是否返回一个jQuery对象?我想直接在jQuery对象上调用子函数,如下所示:'$('#gallery')。imageSlide.nextSlide()';这样我只会污染我的插件的一个“名称空间”(imageSlide),但我不需要跟踪我创建的图像滑块。 – Scharrels 2010-07-25 20:14:20

+0

是的,你可以使用'$('#gallery')。imageSlide()。nextSlide();'链接它们,但是会创建一个新的实例。 – David 2010-07-25 20:26:00