$("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?
$("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?
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>