如何防止事件被多次绑定

时间:2009-06-09 08:55:49

标签: jquery

 $('.ajax').click
 (        
    function()
    {
        // If been bound then we need to return here.
        alert(':D');
    }
 )

 $('.ajax').click
 (
    function()
    {
        // If been bound then we need to return here.
        alert(':D');
    }
 )

在这种情况下,我调用了重复的代码。如何检测事件是否已被绑定以防止它触发两个警告框?

4 个答案:

答案 0 :(得分:24)

在jQuery中有一个非常好的方法。

这是一个例子。

function alertEvent() {
   alert(":D");
}
$(".ajax").bind("click", alertEvent);
//When you want to ensure it won't happen twice...
$(".ajax").unbind("click", alertEvent);
$(".ajax").bind("click", alertEvent);

此方法仅删除您指定的事件,这使其成为您想要做的事情的理想选择。

答案 1 :(得分:19)

如果使用jQuery> = 1.7,您可以将.on()/.off() API与事件命名空间结合使用。在此示例中,立即调用.off()以确保命名空间的先前事件(任何类型)都是未绑定的:

$("form")
    .off(".validator")
    .on("keypress.validator", "input[type='text']", validate);

这是一个非常灵活的API,因此如果你需要,你可以非常具体:

$("form")
    .off("keypress.validator", "input[type='text']", validate)
    .on("keypress.validator", "input[type='text']", validate);

文档: http://api.jquery.com/off/

答案 2 :(得分:7)

在绑定之前尝试解除绑定:

$(".ajax").unbind("click").click( 
      function () { 
    alert("Hello"); 
  } );

阅读this了解更多信息。

答案 3 :(得分:0)

function demo()
{
// your code here which will called on click event
}

$(document).ready(function(){
$('.add').bind('click',demo);

});

//After successfully ajax call response
//Unbind the click event first
$('.add').unbind('click',demo);
//Then again bind the event
$('.add').bind('click',demo);
相关问题