4

Hi I have a Ajax call that I'm doing with jQuery and was wondering what is the difference between these methods on selecting an element on click,

FIRST

$(this).on('click', 'button', function (){ });

SECOND

$('button').on('click', function (){ });

THIRD

$('button').click(function { });

My Ajax call selects new data from my database and updates the content on success and changes the data from a data object that I have on the button with an ID, the first on works but the second and third once both only work once and then it fails and I'm am wondering why, thanks a lot in advance!

Mitchell Layzell
  • 3,058
  • 3
  • 20
  • 33

4 Answers4

4

As per the documentation :

.click()

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

As you showed in your example they are pretty much the same, however you should use the on() method as it allows you to delegate dinamically .

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

Example :

$("#dataTable tbody").on("click", "tr", function(event){
  alert($(this).text());
});

That code will trigger the alert on all the elements that are created within that table, plus if you make AJAX requests and append them to the same table they event handlers will be attached dinamically.

To learn more about how on() delegates check this.

isJustMe
  • 5,452
  • 2
  • 31
  • 47
0

From documentation:

$('button').click(function { });

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

so it's the same what:

$('button').on('click', function { });

Difference between $(this) and $('button') is a scope. In first case you got a handler for element in closure. In second you use selector what mean you attach click event for all button on document.

WooCaSh
  • 5,180
  • 5
  • 36
  • 54
0

You can use .on() to bind an event to an element that doesn't yet exist. For example when You put ajax response into the div, You may define event earlier, bind it to div, but set trigger to some other element.

For example:

$('div').on('click','button',function(){});
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
0

The reason the first one works & not the other 2 is probably because you are over-writing the event when you over-write the button from after your ajax call; which defeats the whole point of using delegation with on(). Either use the first one or recreate the event handler once your ajax call has completed.

Precastic
  • 3,742
  • 1
  • 24
  • 29