Rob L Rob L - 7 months ago 6
Javascript Question

Accessing data("") from dynamically created list items

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

Answer

Well that is strange, since in that context with 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
}