0

This is my code:

$(document).ready(() => {
    $.getJSON("./data/journeys.json", (data) => {
        $.each(data, (i, journey) => {
            $("#journeyListings > tbody").append("<tr class='journeyOrder_" + journey.order + "'>" +
                                                     "<td>" + journey.originStation + "</td>" +
                                                     "<td>" + journey.destinationStation + "</td>" +
                                                     "<td>" + journey.startTime + "</td>" +
                                                     "<td>" + journey.arrivalTime + "</td>" +
                                                 "</tr>")
        });

        $("tr").on("click", () => {
            alert($(this).attr("class"));
        });
    });
});

On the 'click' method, I am trying to reference the row that has just been clicked (tr). When I refer to $(this), it seems that I am referring to the ajax getJson method as I am getting undefined in my alert. How can I reference the element instead?

wmash
  • 4,032
  • 3
  • 31
  • 69

1 Answers1

3

Instead of using the ES6 arrow function, which changes the scoping of this, go back to the long function form:

$('tr').click(function(){
  alert($(this).attr('class'));
});

Of course, if you want to stick with ES6, you should avoid this and use the event's currentTarget property:

$('tr').on('click', (e)=>{
   alert( $(e.currentTarget).attr('class') );
})
BotNet
  • 2,759
  • 2
  • 16
  • 17