41

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.

4

3 に答える 3

57

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.

于 2012-10-06T09:34:48.323 に答える
7

You can try the below code. Also try the jsfiddle too(demo).

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

Try the demo

The answer to your second question is you can assign event to the child and remove from it's parent. Check this out.

.stopPropagation(); 

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more

if you want the specific event to be executed only and allow no other event to be fired you use code below

event.stopImmediatePropagation()

Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. Read more

I hope this will solve your problem. If you have any questions please don't hesitate to ask. Thanks

于 2012-10-06T09:41:38.053 に答える
1

If your elements have grandchildren, there is a better way to get just the child. Note the greater than sign.

$('.parent > .child').click(function() {
    // This will be the child even if grandchild is clicked
    console.log($(this));
});
于 2017-05-30T22:15:53.563 に答える