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. Instead nothing is returned when I click inside the table. I would like to know the id of the div containing the table.

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().

$(event.target).closest('div').attr('id');

Here is an demo: 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.

to get the closest ancestor with an id, you could use this:

http://jsfiddle.net/g6S65/

$(event.target).closest('[id]').attr('id')
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top