The first is a shortcut to
$("button").on('click', function(){
$("button").click(function(){
alert('ok 1');
});
You can check in the source of the official repository alias.js#L10
, this:
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
See that you have this.on( name, null, data, fn )
, .trigger
is only executed if you do not pass function
, do this for example $("...").click();
, which is used to trigger the event.
The second is the "default", and you can also create your own events by using .trigger
$("button").on('click', function(){
alert('ok 2');
});
The third form is actually event delegation,
click
occurs in
#area
, but event is only triggered if element that triggered
click
in
#area
"match" to query of second parameter, ie
button
$('#area').on('click', 'button', function () {
alert('ok 3');
});
The advantage of the third party over others is that you would not have to use things like $.ready
or $(window).load
to set the click event on the button, it already recognizes if the button exists in #area
, since the check of delegation only occurs at the time of the click
The first way to use the click event did not work
What I want to know is why, this is a feature of jquery, it's because of javascript, because sometimes it works and because sometimes it does not work, that's what I wanted to know, I use the events but I do not know why this behavior.
This was probably some confusion of your own, it's unlikely that .on('click')
would work and .click
no, since it's just a shortcut, the only possible possibilities, I believe, for having caused the crash would be:
- A bug in the specific version of jQuery you are using
- Some jQuery add-ons that affected your scripts
- It was just some confusion of yours, maybe other events with
stopPropagation
or something similar that prevented it and you removed them when you switched to .on
without realizing it.
But my "technique" is as follows, I try the first, it does not work I go to second and in turn it did not work step to third.
I personally would always choose the third one, it's simple, you do not need to check if the DOM exists, if you create a new element it will work, removing it will not have to do much if you need any element with a specific class or attribute on the page to have the event just use document
, example:
$(document).on('click', '#area button', function () {
alert('ok 3');
});
Or so (in this case elements with classes foo and bar will trigger the event):
$(document).on('click', '.foo, .bar', function () {
alert('ok 3');
});