Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

javascript - jQuery click event on parent, but finding the child (clicked) element

let say I have a parent element which has so many nested child elements inside of itself:

<div id="p">
    <div id="c1">
        <div id="c2"></div>
        <div id="c3"></div>
    </div id="c4">
        <div id="c5"></div>
    </div>
</div>

I've already bind a click event on the parent:

$('#p').bind('click', function() {
    alert($(this).attr('id'));
});

Because the event is assigned to the parent element, I always see the parent id, however, I'm wondering if there is any possible way to find out which of this child elements has been clicked?

I also can't assign any event to the child elements or remove the event listener from parent div.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to pass event object to function to get the item that triggered the event, event.target will give you the source element.

Live Demo

 $('#p').bind('click', function(event) {
    alert(event.target.id);
 });

or

Live Demo

$('#p').bind('click', function(event) {
    alert($(event.target).attr('id'));
});

Edit

The first method event.target.id is preferred over second $(event.target).attr('id') for performance, simplicity and readability.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...