如何防止事件被多次绑定 [英] How to prevent events from being bound multiple times

查看:77
本文介绍了如何防止事件被多次绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 $('.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');
    }
 )

在这种情况下,我称重复代码.如何检测事件是否已绑定以防止触发两个警报框?

In this case, I have called duplicate code. How do I detect if the event has been bound to prevent it from triggering two alert boxes?

推荐答案

在jQuery中有一种非常好的方法.

There's a really good way to do this in 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);

此方法只会删除您指定的事件,因此非常适合您要执行的操作.

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

这篇关于如何防止事件被多次绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆