2015-08-25 56 views
0

我使用「關閉事件」來避免多個AJAX請求(例如,如果用戶做了多次點擊)。完美的作品。jQuery - 關()不依賴於事件

問題是,根據「on('click')」事件的調用方式,事件off()根本不起作用。我舉一個例子:

功能:

var addComment(elem) = function(){ 
    $.ajax({ 
     type: "POST", 
     url: '../../ajax/request.php', 
     dataType: 'json', 
     data: data, 
     beforeSend: function(){ 
      // after this line, click the elem doesn't do anything 
      elem.off('click'); 
     }, 
     success: function(result){ 
      if (result.success){ 
       console.log('success!'); 
      }else{ 
       console.log('no success...'); 
      } 
      //making "elem" clickable again 
      elem.on('click',function(){ 
       addComment(elem); 
      }); 
     }, 
     error: function(xhr, ajaxOptions, thrownError){ 
      alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError); 
     } 
    }); 
} 

活動:

// Using this, the off event works normally 
$('.divArea button.newComment').on('click',function(){ 
    addComment($(this)); 
}); 

// Using this, the off event simply is not executed 
$('.divArea') 
    .on('click', 'button.newComment',function(){ 
     addComment($(this)); 
    }) 

爲什麼在第二種情況下,關閉()不工作,我應該做到off()在兩個事件調用示例中都能正常工作?

謝謝先進。

+2

您的函數定義語法是錯誤的,該代碼如何運行? – Barmar

+0

它應該是'var addComment = function(elem){...}'或'function addComment(elem){...}' – Barmar

+0

在ajax之後單擊並重新啓用時禁用該按鈕會更簡單嗎?返回? –

回答

0

第二個版本不起作用的原因是因爲當您使用委派時,事件綁定不在按鈕上,它實際上是.divArea。委派的工作方式是讓處理程序自動檢查事件的目標是否與您委派的選擇器匹配 - 這就是它能夠擴展到綁定建立時不存在的元素的方式。

由於沒有單個元素的綁定,因此無法使用.off將其刪除。

你可以做的是委託給一個具有類的選擇器,並在處理事件時改變類。

$('.divArea').on('click', 'button.newComment:not(.handled)', function() { 
    addComment($(this)); 
}); 

function addComment(elem) { 
    $.ajax({ 
     type: "POST", 
     url: '../../ajax/request.php', 
     dataType: 'json', 
     data: data, 
     beforeSend: function(){ 
      // after this line, click the elem doesn't do anything 
      elem.addClass("handled"); 
     }, 
     success: function(result){ 
      if (result.success){ 
       console.log('success!'); 
      }else{ 
       console.log('no success...'); 
      } 
      //making "elem" clickable again 
      elem.removeClass("handled"); 
     }, 
     error: function(xhr, ajaxOptions, thrownError){ 
      alert("Error Status: " + xhr.status + " Thrown Errors: "+thrownError); 
     } 
    }); 
} 
+0

所以基本上,沒有直接使用第二個事件示例來「關閉」一個元素?如果沒有辦法去掉元素,我只會使用第一個示例,因爲它完全適合。順便說一句,非常感謝你的回答。我沒有找到解釋爲什麼off()失敗時,我GOOGLE了它。 –

+0

通常你使用第二個版本,因爲你正在動態創建元素。第一個版本不適用於動態添加的元素。 – Barmar