查找到相关的表onclick事件

问题描述:

的TD我有一个像下面查找到相关的表onclick事件

<table onclick="dosomething()"> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
</table> 

后,我点击表的表,我需要找到在其上点击发生的TD。我不能在tr或td上写上onclick事件。

+1

我认为事件只注册为从表中发起。 – 2011-12-16 13:29:27

+1

您可以使用`event.target`,但不应该使用内联处理程序。 – pimvdb 2011-12-16 13:30:16

$(function(){ 
    $("#tbl").bind("click", function(e){ 
     if(e.target.tagName == "TD"){ 
      //do your magic 
     } 
    }); 
}); 

你可以做这样的事情(给你table一类myClass - 或任何你想要的):

function tableClicked(td) { 
    // Do something dependent on the td which was clicked 
} 

$(document).ready(function() { 
    $("table.myClass td").click(function() { 
     tableClicked(this); 
    }); 
}); 

这意味着你不必onclick属性添加到<td>标签。

+0

嗯,他仍然在添加它们......(只是没有手动添加标记!) – 2011-12-16 13:33:40

我会倾倒的onclick并为此

$("#myTable td").click(function() { 
    $(this).html(); // get the value 
    $(this).hide(); // hide it 
    $(this).remove(); // remove it 
}); 

<table id="myTable"> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
</table> 

的ID添加到表和删除的onClick处理程序。这是为了分离行为和内容。

<table id="tableId"> 

因为事件会冒泡,捕捉到它的表体上,找到目标,所以你不需要事件侦听器添加到每个TD。

$('#tableId').click(function(e){ 
    //the td is the target where event happens 
    var td=e.target; 
});