2015-08-25 46 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