[英]Target ID for Div not propagating
With a table inside a div, I thought the target ID would propagate up when I try to find what target triggered the click event. 使用div中的表,我认为当我尝试找到触发click事件的目标时,目标ID会传播。 Instead nothing is returned when I click inside the table. 相反,当我在表格内单击时,不会返回任何内容。 I would like to know the id of the div containing the table. 我想知道包含表格的div的id。
http://jsfiddle.net/UWm46/ http://jsfiddle.net/UWm46/
$(document).click(function(event) {
alert("Target ID: " + event.target.id);
});
<div id='box3'>
box 3
<table><tr><td>table 3</td></tr></table>
</div>
You'd want to use .closest()
. 你想使用.closest()
。
$(event.target).closest('div').attr('id');
Here is an demo: http://jsfiddle.net/UWm46/3/ 这是一个演示: http : //jsfiddle.net/UWm46/3/
When you click the "table 3" text, the target is the td
, and the td
doesn't have an ID. 单击“表3”文本时,目标是td
,而td
没有ID。
to get the closest ancestor with an id, you could use this: 要获得具有id的最近祖先,您可以使用:
http://jsfiddle.net/g6S65/ http://jsfiddle.net/g6S65/
$(event.target).closest('[id]').attr('id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.