2012-06-27 24 views
0

我嘗試在一個元素上設置超時,使用jQuery插件觸發。根據條件,該超時在功能中再次設置。但是,在設置另一個(如果我重新啓動插件)之前,我想先清除此元素的超時值,或者手動清除此元素。清除在jQuery插件中啓動的非全局超時

<div id="aaa" style="top: 0; width: 100px; height: 100px; background-color: #ff0000;"></div>

這裏是我的代碼(現在http://jsfiddle.net/Ppvf9/

$(function() { 

    $('#aaa').myPlugin(0); 

}); 



(function($) { 


$.fn.myPlugin = function(loops) { 

    loops = loops === undefined ? 0 : loops; 

    this.each(function() { 

     var el = $(this), 
      loop = loops, 
      i = 0; 

     if (loops === false) { 
      clearTimeout(el.timer); 
      return; 
     } 

     var animate = function() { 
      var hPos = 0; 
      hPos = (i * 10) + 'px'; 

      el.css('margin-top', hPos); 
      if (i < 25) { 
       i++; 
      } else { 
       if (loops === 0) { 
        i = 0; 
       } else { 
        loop--; 
        if (loop === 0) { 
         return; 
        } else { 
         i = 0; 
        } 
       } 
      } 

      el.timer = window.setTimeout(function() { 
       animate(); 
      }, 1000/25); 

     }; 

     clearTimeout(el.timer); 

     //$('<img/>').load(function() { 
      // there's more here but it's not very important 
      animate(); 
     //}); 

    }); 
    return this; 

}; 


})(jQuery); 

如果我讓$('#element').myPlugin();,它的推出。如果我再來一次,則有兩次超時(在控制檯中通過執行$('#aaa').myPlugin(0); 來查看)。我希望能夠通過$('#element').myPlugin(false);來解決這個問題。

我在做什麼錯?

編輯: 解決通過調節兩個變種訪問this$(this)這裏:http://jsfiddle.net/Ppvf9/2/

回答

0

嘗試保存超時處理函數作爲元素的屬性。或者維護一個將元素映射到其超時句柄的靜態查找表。

事情是這樣的:


el.timer = window.setTimeout(...); 

我認爲你需要每個元素一個計時器。對於所有元素不是一個計時器。

+0

你的意思是......使計時器var屬性'el'? (我怎麼能?) – Joan

+0

我編輯了我的答案 – akonsu

+0

嗯,我試着在函數中添加'clearTimeout(el.timer);',並在if === false條件下(用'el.timer = window.setTimeout (...); '),它不起作用... – Joan