Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

javascript - jQuery - Detect TD ID on click

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

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

1 Reply

0 votes
by (71.8m points)

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);
     // ...
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...