jQuery 2.2.3
I have a dynamic list of elements, that get created/removed on the fly:
<ul id="tracks">
<button class="createRace" data-trackcode="410243">Create Race</button>
<button class="createRace" data-trackcode="123540">Create Race</button>
...
</ul>
I am using the following technique to react to button clicks.
$("#tracks").on("click", ".createRace", createRaceClick);
My createRaceClick() function is being called, but the "this" object is referencing #tracks, not the button that was pressed.
How can I determine which button was pressed? Or more specifically, how can I get the data("trackcode") associated with the actual button that was pressed.
Thanks
Well that is strange, since in that context of event delegation, this should refer to the button that was clicked. However you can use target property of the event object to get the .createRace that raised the click event:
$("#tracks").on("click", ".createRace", createRaceClick);
function createRaceClick(e){
var data=$(e.target).data('trackcode'); // $(this).data('trackcode') should work
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With