绑定相同的事件两次将在jQuery 1.4.2中触发两次

Adr*_*ciu 4 jquery events

如果你有这样的东西:

jQuery(selector).focus(function(){...});
jQuery(selector).focus(function(){...});
Run Code Online (Sandbox Code Playgroud)

焦点会触发两次,无论如何我可以纠正/防止这种情况吗?

Dav*_*ing 8

使用data('events')查找事件处理程序:

var isBound = function(el, ev) {
    var found = false;
    $.each($(el).data("events"), function(i, e) {
        if (i === ev) {
            found = true;
        }
    });
    return found;
}

if (!isBound(selector, 'focus')) {
    $(selector).bind('focus', fn);
}
Run Code Online (Sandbox Code Playgroud)

你也可以.one()在jQuery中使用这个函数,看看http://api.jquery.com/one/