3
$("body").on('click', 'ul#ajax-users-list>li', () => {
    console.log( $(this).data('id') );
});

This code returning undefined, because $(this) = [Window].

How can i access data attributes for element, that triggered click event?

Src
  • 5,252
  • 5
  • 28
  • 56

1 Answers1

6

The issue is because you're using an arrow function, therefore the scope of the handler function will remain at the level of the definition. If you use a traditional anonymous function the logic will work fine:

$("body").on('click', 'ul#ajax-users-list>li', function() {
  console.log($(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ajax-users-list">
  <li data-id="foo">click me</li>
</ul>

If you'd prefer to use the arrow function, then you would need to get the element that raised the event from the provided event argument instead of the this reference:

$("body").on('click', 'ul#ajax-users-list>li', (e) => {
  console.log($(e.target).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ajax-users-list">
  <li data-id="foo">click me</li>
</ul>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • nice one +1 bro – Dalin Huang Jul 13 '17 at 20:12
  • This could be improved by explaining that [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) don't bind their own `this` (and `arguments`, etc.). – Makyen Jul 13 '17 at 20:26