1

I have the following code creating a td

html += "<td data-id='test' class='journal' style='max-width:200px;'>"+record.source_account_code+"</td>";

and then the following code

    $(document).on('click', '#table-content td', e => {
   console.log("td onclick called")
   console.log($(this).attr('data-id'))
});

which executes correctly but instead of outputting "test" I get "undefined"

I have tried doing it this way as well

$(this).data("id")
Murphstar
  • 99
  • 6

1 Answers1

3

Use a regular function, not an arrow function:

$(document).on('click', '#table-content td', function() {
  console.log("td onclick called")
  console.log($(this).attr('data-id'))
});


document.querySelector('#table-content').innerHTML += "<td data-id='test' class='journal' style='max-width:200px;'>record</td>";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table-content"></table>

This is because jQuery will bind the event target to the function, which is why this will refer to the element. You can't bind to an arrow function however. It's an ES6 quirk.

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 2
    For OP, there is more reading [here](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable/34361380#34361380) – Louys Patrice Bessette Dec 18 '22 at 23:18