2010-07-25 136 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