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")
CodePudding user response:
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.