单击TR时确定目标TD

时间:2011-09-06 13:56:07

标签: javascript jquery

给出表行的点击事件:

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

我可以确定点击时光标下面的TD(或任何子元素)吗?

3 个答案:

答案 0 :(得分:5)

如果您能够更改脚本,请执行此操作以利用jquerys .delegate功能。这避免了多个绑定的单击事件,并且在事件处理程序中,此上下文将是单击的td元素的上下文。

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

   //this refers to the td

})

答案 1 :(得分:4)

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

要查找点击的<td>而不考虑任何子元素,请改用var target = $(e.target).closest("td");

答案 2 :(得分:2)

一对夫妇大多是正确的答案,但是一个人错过了最接近的答案,另一个人做了很多不必要的错误处理。

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