2012-03-19 115 views
1

大家好。

我想開發一個jquery插件,遵循我在http://docs.jquery.com/Plugins/Authoring中發現的步驟,並且我在傳遞給插件的選項內似乎遇到了調用者對象(「this」變量)的問題。這是一個插件,我只是想用來使按鈕具有「閃爍」效果。

我希望能夠將該功能作爲插件的選項傳遞給「顯示/隱藏」(或者,如果您願意,可以鏈接閃爍,閃爍)。假設用戶希望通過每1000毫秒隱藏/顯示整個按鈕來實現「閃爍」效果。然後我想的選項是這樣的:

$("#bttnOk").myBlinker ({ 
    blinkHide: function(){$(this).hide();}, 
    blinkShow: function(){ $(this).show();}, 
    interval:1000 
}); 
// … // 
// And to make it actually blink: 
$("#bttnOk").myBlinker ("blink"); 

還是讓我們說,用戶希望移動的按鈕向上和向下施加內嵌CSS sytle每200ms。然後選擇辦法是這樣的:

$("#bttnOk").myBlinker ({ 
    blinkHide: function(){$(this).css(「margin-top: 10px」);}, 
    blinkShow: function(){ $(this).css(「margin-top: 0px」);}, 
    interval:200 
}); 

的問題是,我似乎失去所提到的「$(本)」當我的選項內。當插件到達blinkHide/blinkShow函數時,「this」是整個DOM窗口,而不是我的「myBlinker」插件附帶的按鈕$(「#bttnOk」)。

這是我試圖寫的第一個jquery插件,所以我甚至不知道是否有辦法實現我想要做的事情。

我的插件代碼遵循以下結構:

(function($){ 
    var defaultOptions = { 
     interval: 500 
    } 

    var methods = { 
     init : function(options) { 
      return this.each(function(){ 
       this.options = {} 
       $.extend(this.options, defaultOptions, options); 
       var $this = $(this); 
       var data = $this.data('myBlinker'); 

       // If the plugin hasn't been initialized yet 
       if (! data) { 
        $this.data('myBlinker', { 
         on : true 
        }); 
       } 
      }); 
     }, 
     destroy : function() { // Some code here}, 
     blink: function (){ 
      console.log("Blinking!. This: " + this); 
      var current = 0; 
      var button=this.get(0); 
      setInterval(function() { 
       if (current == 0){ 
        button.options["blinkShow"].call(this); 
        current=1; 
       } else { 
        button.options["blinkHide"].call(this); 
        current=0; 
       } 
      }, button.options["interval"]); 
     } 

    }; 

    $.fn. myBlinker = function(method) { 
     // Method calling logic 
     if (methods[method]) { 
      return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); 
     } else if (typeof method === 'object' || ! method) { 
      return methods.init.apply(this, arguments); 
     } else { 
      $.error('Method ' + method + ' does not exist on jQuery.myBlinker '); 
      return null; 
     } 
    }; 
})(jQuery); 

任何想法,校正,鏈路或尖端將受到讚賞。

謝謝。

回答

4

setInterval函數中,this是全局對象,而不是像blink函數中的當前元素DOMElement。

的解決方案是保存的this參考,使用保存在的setInterval參考:

blink: function (){ 

     // save a reference of 'this' 
     var that = this; 

     setInterval(function() { 

      // use the saved reference instead of 'this' 
      button.options["blinkShow"].call(that); 

     }, button.options["interval"]); 
    } 

DEMO

+0

是的...這是工作。我覺得有點愚蠢。我應該知道我自己。謝謝,Didier – BorrajaX 2012-03-20 15:00:54

+0

很高興幫助;-) – 2012-03-20 16:50:30

相關問題