我使用「關閉事件」來避免多個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()在兩個事件調用示例中都能正常工作?
謝謝先進。
您的函數定義語法是錯誤的,該代碼如何運行? – Barmar
它應該是'var addComment = function(elem){...}'或'function addComment(elem){...}' – Barmar
在ajax之後單擊並重新啓用時禁用該按鈕會更簡單嗎?返回? –