如何检查事件是否绑定到元素,以防止重复绑定?

ilg*_*aar 0 jquery events bind

我有一个函数,基本上创建一个覆盖整个页面的叠加div元素.它还将resize事件绑定到窗口,因此每当调整窗口大小时,叠加层也会更改其大小:

function stdOverlay() {
    var overlay = $('<div />').css({width : $(window).width(), height : $(window).height()});
    var overlayResize =
    function() {
        $(overlay).css({width : $(window).width(), height : $(window).height()});
    };
    $('body').append(overlay);
    $(window).resize(overlayResize);
    //... other codes,  like remove overlay and unbind the events
    //$('div.stdgui-overlay').unbind('resize', overlayResize);
}
Run Code Online (Sandbox Code Playgroud)

每次调用该函数时,如果没有,则添加一个叠加层,并将resize事件绑定到窗口.当它应该删除重叠事件时,它也会取消绑定事件.如果overlayResize方法绑定到window元素,如何防止重复绑定?就像是:

    if(overlyResize is not bound to window)
        $(window).resize(overlayResize);
    else
        //do something else or do nothing;
Run Code Online (Sandbox Code Playgroud)

ade*_*neo 5

你可以使用一个标志,但最简单的方法就是取消绑定然后重新绑定事件以确保它只绑定一次:

$(window).off('resize', overlayResize).on('resize', overlayResize);
Run Code Online (Sandbox Code Playgroud)