Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to get a TD ID when I'm clicking on a table's row.

I've searched for ways to realize this, and found a way. But everytime I'm clicking, an alert pops up but it's an empty text. Using the console I saw that's the error code is "undefined".

Here's my code :

function chooseCell() {
let square = 0;
let squareNumber = 0;
$("td").click((e) => {
    let data = $(this).attr('id');
    alert (data);
    for (square in squarePositions) {
            squareNumber += 1;
            if (square[1] <= e.pageX <= square[3] && square[0] <= e.pageY <= square[2]) {
                alert(squareNumber);
                alert("Square Number : " + squareNumber);

            }
        }
    }
)}

If I replace the alert(data) by :

alert($('td').attr('id'));

The alert pops up the first table's TD. Whenever I click on a different TD, the first ID is displayed

Does someone know how to display the current clicked id ? There were no answers for my problem on Google and SOF

Thank you very much, best regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
313 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are using an arrow function for your event handler.

An arrow function does not newly define its own this when it's being executed in the global context; instead, the this value of the enclosing execution context is used, equivalent to treating this as closure value.

$("td").click((e) => {
    let data = $(this).attr('id');
    alert (data);
     // ...
});

Hence in your code this doesn't refer to the td as you expect it to. You can use the event.target to access the td with the following code

let data = $(e.target).attr('id');

Or you can also use a regular function instead of the arrow function and now this would refer td

$("td").click(function(e){
    let data = $(this).attr('id');
    alert (data);
     // ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...