jquery use of bind vs on click

前端 未结 3 981
無奈伤痛
無奈伤痛 2020-12-02 12:54

I have come across several methods for handling click events in jquery:

bind:

$(\'#mydiv\').bind(\'click\', function() {
    ...
});
<
3条回答
  •  广开言路
    2020-12-02 13:33

    From the documentation of bind and click :

    bind :

    As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

    The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :

    bind: function( types, data, fn ) {
        return this.on( types, null, data, fn );
    },
    

    So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.

    click :

    This method is a shortcut for .on('click', handler)

    This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?

提交回复
热议问题