0

my jQuery not work and $(this) refers to document

$(function(){
  $('.delete').on('click', (e)=> {
    console.log($(this).data('id'));
  });

  // or

  $('.delete').click( (e)=> {
    console.log($(this).data('id'));
  });
});

So I try this and it works because $(this) refers to true element:

$('.delete').click( function () {
  console.log($(this).data('id'));
});

// or 

$('.delete').on('click', function () {
  console.log($(this).data('id'), $(this).val());
});

What is the reason for that?

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
xpredo
  • 1,282
  • 17
  • 27
  • 1
    This is expected, the arrow function in JS `=>` is not equivalent to a traditional function, as the context of `this` is different. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Eric Phillips Jun 25 '21 at 14:05
  • 1
    "What is the reason for that?" — Because treating `this` differently is 90% of the point of arrow functions existing. – Quentin Jun 25 '21 at 14:07
  • You can get the element you expect from `e.target` in both types of functions, and not worry about `this` any more. – James Jun 25 '21 at 14:24

0 Answers0