简体   繁体   中英

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

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