2011-10-22 52 views
1

我有這樣的jQuery的事件:如何防止前一個事件的執行,直到最後通話完畢

$('#button-next').bind('click', function() { 
    $.ajax({ 
     type: "GET", 
     dataType: "json", 
     url: 'index.php?route=product/category/display&cat=any&limit='+p+',1', 
     cache: false, 
     success: function(data) { 
      var text = data.output; 
      goForward('scroller', text); 
      p++; 
     } 
    }); 
}); 

即插入一個新的項目列表,並刪除最後一個。問題是如果用戶開始快速點擊按鈕,它會變得混亂。我需要一種方法來防止在最後一次完成之前發出新的呼叫。

回答

2

你可以使用.one()方法訂閱點擊動作:

$('#button-next').one('click', process); 

在那裏你可以定義process功能是這樣的:

function process() { 
    $.ajax({ 
     type: 'GET', 
     dataType: 'json', 
     url: 'index.php', 
     cache: false, 
     data: { 
      route: 'product/category/display', 
      cat: 'any', 
      limit: p + ',1' 
     }, 
     success: function(data) { 
      var text = data.output; 
      goForward('scroller', text); 
      p++; 
      // we rebind the click event once again 
      $('#button-next').one('click', process); 
     } 
    }); 
} 
+2

而不是'$('#button-next')。clic k(函數()''你可以使用'$('#button-next')。'('click',function()'。這使得解綁無用,並保存一行 – topek

+1

@topek,絕妙的想法。我已更新我的帖子,將您的評論納入考慮範圍。感謝您指出了這一點。 –

1

禁止在點擊該按鈕後啓用ajax complete

  $('#button-next').bind('click', function() { 
       $('#button-next').attr('disabled', 'disabled'); 
       $.ajax({ 
        type: "GET", 
        dataType: "json", 
        url: 'index.php?route=product/category/display&cat=any&limit='+p+',1', 
        cache: false, 

        success: function(data) { 
          $('#button-next').removeAttr('disabled') 
          var text = data.output; 
          goForward('scroller', text); 
          p++; 
        } 
       }); 
      }); 
相關問題