我使用"off事件"来避免多个AJAX请求(例如,如果用户进行多次单击)。完美的工作。
问题是,取决于如何"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()不起作用,我应该对off()做些什么,在两个事件调用示例中都能正常工作?
第二个版本不起作用的原因是因为当你使用委托时,事件绑定不在按钮上,它实际上是在.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);
}
});
}