0

for the life of me i can't understand why my code doesn't work...

<!-- language: lang-html -->
<table id='table'>
   <tr id='some-id'>
      <td>some data</td>
      <td>some data</td>
   </tr>
</table>

my first attempt:

<!-- language: lang-js -->
$(() => {
    $('#table tr').on('click', () => {
        console.log($(this).prop('id'))
    }
}

second thoughts:

<!-- language: lang-js -->
$(() => {
    $('#table').on('click', 'tr', () => {
        console.log($(this).attr('id'))
    }
}

it keeps returning undefined

i feel really dumb for messing this up, any help would be massive right now thanks in advance!

  • `this` has [different scope](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in arrow functions. – isherwood Feb 27 '18 at 17:41
  • 2
    See the linked dupetarget, arrow functions **close over** `this`, they don't get it from how they're called like other functions, so jQuery can't set `this` to the element. Your first code snippet is correct, just use a `function` function in it instead of an arrow. (Side note: `$(this).prop("id")` is a really long-winded way to write `this.id`. ;-) ) – T.J. Crowder Feb 27 '18 at 17:41

0 Answers0