简体   繁体   中英

Determining target TD when TR is clicked

Given some click event for a table row:

$("tr.somerow").click(function(){
    //do some stuff
    //can I determine the TD under the cursor at the time of clicking?
})

Can I determine which TD (or any child elements) was under the cursor at the time of clicking?

If you are able to change the script then do so to take advantage of jquerys .delegate function. This avoids having multiple bound click events and also in the event handler the this context will be that of the clicked td element.

$('tr.somerow').delegate('td', 'click', function(){

   //this refers to the td

})
$("tr.somerow").click(function(e){
  var target = $(e.target); // sets to the td or the element that was clicked
  //do some stuff
})

To find the clicked <td> regardless of any child elements, use var target = $(e.target).closest("td"); instead.

A couple mostly correct answers, but one misses the closest, and the other does a lot of unnecessary error handling.

$("tr.selector").click(function(e){
    var td = $(e.target).closest('td');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM