jQuery: $().click(fn) vs. $().bind('click',fn);

前端 未结 7 1741
北荒
北荒 2020-11-28 03:37

When using jQuery to hookup an event handler, is there any difference between using the click method

$().click(fn)

versus using the bind me

相关标签:
7条回答
  • 2020-11-28 03:44

    If you have Google Chrome, their developer tools have an event listener tool, select the element you want to spy its' event.

    You'll find that trying the both ways lead to the same result, so they are equivalent.

    0 讨论(0)
  • 2020-11-28 03:49

    I prefer .bind() because of its interface consistency with .live(). Not only does it make the code more readable, but it makes it easier to change a line of code to use one method instead of the other.

    0 讨论(0)
  • 2020-11-28 03:51

    There is one difference in that you can bind custom events using the second form that you have. Otherwise, they seem to be synonymous. See: jQuery Event Docs

    0 讨论(0)
  • 2020-11-28 03:58

    For what it's worth, from the jQuery source:

    jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
        "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
        "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
    
        // Handle event binding
        jQuery.fn[name] = function(fn){
            return fn ? this.bind(name, fn) : this.trigger(name);
        };
    });
    

    So no, there's no difference -

    $().click(fn)
    

    calls

    $().bind('click',fn)
    
    0 讨论(0)
  • 2020-11-28 03:58

    I find the .click() is way more logical, but I guess it's how you think of things.

    $('#my_button').click(function() { alert('BOOM!'); });
    

    Seems to be about as dead simple as you get.

    0 讨论(0)
  • 2020-11-28 04:03

    There is the [data] parameter of bind which will occur only at bind-time, once.

    You can also specify custom events as the first parameter of bind.

    0 讨论(0)
提交回复
热议问题