jQuery插件子函数中的无限递归
我编写了以下jQuery插件:jQuery插件子函数中的无限递归,jquery,jquery-plugins,infinite-loop,Jquery,Jquery Plugins,Infinite Loop,我编写了以下jQuery插件: (function($){ $.fn.imageSlide = function(options){ $(this).imageSlide.nextSlide(); console.log("imageslide"); }; $.fn.imageSlide.nextSlide = function(){ console.log("nextslide"); $this = $(this);
(function($){
$.fn.imageSlide = function(options){
$(this).imageSlide.nextSlide();
console.log("imageslide");
};
$.fn.imageSlide.nextSlide = function(){
console.log("nextslide");
$this = $(this);
};
})(jQuery);
一些背景:
我想要一个图像滑块插件,以交叉淡入背景(出于性能原因,我不能使用该插件)。我想向用户公开几个函数:imageSlide插件“构造函数”和其他几个函数,例如imageSlide.nextSlide
和imageSlide.previousSlide
,以使用户能够从插件外部执行这些操作
imageSlide
函数需要调用imageSlide.nextSlide函数
,以滑入(或淡入)第一张图像
问题:
似乎行$this=$(this)
触发imageSlide.nextSlide
函数的无限递归
- 为什么会这样
- 似乎
不是在jQuery插件中公开另一个函数的正确方法。我该怎么做$.fn.imageSlide.nextSlide=function(){}
(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();
这是否返回jQuery对象?我想直接在jQuery对象上调用子函数,如下所示:
$(“#gallery”).imageSlide.nextSlide()
;这样,我的插件只污染了一个“名称空间”(imageSlide),但我不需要跟踪我创建的图像滑块。是的,您可以使用$('#gallery').imageSlide().nextSlide()将它们链接起来代码>但这将创建一个新实例。