Javascript jQuery单击父级事件,但找到子(单击)元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12758547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery click event on parent, but finding the child (clicked) element
提问by Mahdi
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:
我已经click
在父级上绑定了一个事件:
$('#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?
因为事件被分配给父元素,所以我总是看到父 id,但是,我想知道是否有任何可能的方法来找出哪个子元素被点击了?
I also can't assign any event to the child elements or remove the event listener from parent div.
我也无法将任何事件分配给子元素或从父 div 中删除事件侦听器。
回答by Adil
You need to pass event object to function to get the item that triggered the event, event.target will give you the source element.
您需要将事件对象传递给函数以获取触发事件的项目, event.target 将为您提供源元素。
$('#p').bind('click', function(event) {
alert(event.target.id);
});
or
或者
$('#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.
第一种方法event.target.id
在$(event.target).attr('id')
性能、简单性和可读性方面优于第二种方法。
回答by Techie
You can try the below code. Also try the jsfiddle too(demo).
你可以试试下面的代码。也可以尝试 jsfiddle(演示)。
$('#p').on('click', function(event) {
alert(event.target.id);
});?
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
防止事件在 DOM 树中冒泡,从而防止任何父处理程序收到该事件的通知。阅读更多
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
阻止其余的处理程序被执行,并防止事件在 DOM 树上冒泡。阅读更多
I hope this will solve your problem. If you have any questions please don't hesitate to ask. Thanks
我希望这能解决你的问题。如果您有任何问题,请随时提出。谢谢
回答by Eddie
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));
});