2014-02-22 29 views
0

在按鈕點擊,我改變一個單選按鈕點擊一個按鈕往往使得事件綁定就會失控

$('#left').click(function(){ 
    move(-1) 
}) 
$('#right').click(function(){ 
    move(1) 
}) 


function anim_loop(index) { 
    if(index == $elements.length){ 
     index = 0; 
    } 
    if(timer){ 
     $elements.filter('.current').stop(true, true).hide().removeClass('current'); 
     clearTimeout(timer) 
    } 
    $radios.eq(index).prop('checked', true); 
    $elements.eq(index).stop(true, true).addClass('current').fadeIn(1000, function() { 
     var $self = $(this); 
     timer = setTimeout(function() { 
      $self.fadeOut(1000).removeClass('current'); 
      anim_loop((index + 1) % $elements.length); 
      timer = undefined; 
     }, 3000); 
    }); 
} 

的選擇的價值,但是當我點擊「右鍵」按鈕太快,整個單選按鈕選擇循環去幹擾。可能的解決辦法是什麼?

http://jsfiddle.net/69nk3/3/

回答

1

試試這個

$('#left').click(function(){ 
    $(this).clearQueue(); 
    $('#right').stop().clearQueue(); 
    move(-1); 
}) 
$('#right').click(function(){ 
    $(this).clearQueue(); 
    $('#left').stop().clearQueue(); 
    move(1); 
}) 
+0

是它的工作。你能解釋發生了什麼嗎?順便說一句,如果您隨機單擊單選按鈕,也會發生相同的行爲。任何想法如何解決這個問題? – Philtho

+0

是的,當然。這是由事件監聽者重新綁定發生的。我們只是在註冊另一個事件之前從內存中清除它。在所有複雜的事件監聽器之前使用它是一個很好的實踐。 $(本).clearQueue();如果你想停止與另一個動畫混合的動畫,則使用它。 。$( '#animated_element')停止()clearQueue();在您即將動畫的動畫代碼的開頭。因此,所有#animated_element將被阻止,當前動畫將開始。 – Vilvan