Rob L Rob L - 1 year ago 56
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>

I am using the following technique to react to button clicks.

$("#tracks").on("click", ".createRace", createRaceClick);

function is being called, but the "this" object is referencing
, not the
that was pressed.

How can I determine which button was pressed? Or more specifically, how can I get the
associated with the actual button that was pressed.


Answer Source

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=$('trackcode'); //  $(this).data('trackcode') should work
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download