如何防止事件被多次绑定

Ant*_*thy 18 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');
    }
 )
Run Code Online (Sandbox Code Playgroud)

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

Fen*_*ton 26

在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);
Run Code Online (Sandbox Code Playgroud)

此方法仅删除您指定的事件,这使其成为您想要执行的操作的理想选择.


Pet*_*e B 20

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

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

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

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

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


The*_*iot 9

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

$(".ajax").unbind("click").click( 
      function () { 
    alert("Hello"); 
  } );
Run Code Online (Sandbox Code Playgroud)

阅读本文以获取更多信息.


小智 5

从这里最简单的解决方案只绑定一次事件

复制的代码示例:

function someMethod()
{
    $(obj).off('click').on('click', function(e) {
        // put your logic in here 
    });
}
Run Code Online (Sandbox Code Playgroud)