99Problems 99Problems - 4 months ago 7
jQuery Question

jQuery - difference between these function calls

I have a JS-class with some events

jQuery(document).on('click', '.btn-details', (e) => {


but I can't access the data-attr tthe
.btn-details
has.

when I do a

jQuery(document).on('click', '.btn-details', function() {


I can access the data-attr of the
btn-details
-element, but not the
this.myvar
-class-variable.

what is the problem here? what does this
(e) =>
exactly mean?

Answer

e contains the click event properties. it's commonly used with an global-like (document scoped) event like this:

jQuery(document).on('click', '.btn-details', (e) => {
   var btnDetails = e.target;
   var attr = btnDetails.data("attr");
}

or

jQuery(document).on('click', '.btn-details', function(e) {
   var btnDetails = e.target;
   var attr = btnDetails.data("attr");
}

the original event receiver is the document element, because you had bound the listener method to it, but you can get the triggering element by querying e.target inside it.

Comments