How to prevent events from being bound multiple times

后端 未结 5 1361
后悔当初
后悔当初 2021-01-01 15:10
 $(\'.ajax\').click
 (        
    function()
    {
        // If been bound then we need to return here.
        alert(\':D\');
    }
 )

 $(\'.ajax\').click
 (
            


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-01 15:57

    There's a really good way to do this in jQuery.

    Here's an example.

    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);
    

    This method will only remove the event you specify, which makes it ideal for what you want to do.

提交回复
热议问题