let say I have a parent element which has so many nested child elements inside of itself:
-
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.
讨论(0)
-
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
讨论(0)
-
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));
});
讨论(0)
- 热议问题