jQuery在父项上单击事件,但找到子(点击)元素 [英] jQuery click event on parent, but finding the child (clicked) element

查看:519
本文介绍了jQuery在父项上单击事件,但找到子(点击)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个父元素,其内部有很多嵌套的子元素:

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

我已经绑定了一个点击事件在父母上:

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

由于事件分配给父元素,我总是看到父ID,我想知道是否有任何可能的方法来找出哪些孩子元素被点击了?



我也不能将任何事件分配给子元素或删除事件侦听器从父div。

解决方案

您需要传递事件对象才能获取触发事件的事件事件。目标将给您源元素。



Live Demo

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



现场演示

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

修改



第一个方法 event.target.id 优于第二个 $(event.target).attr('id')的性能,简单性和可读性。


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.

解决方案

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.

这篇关于jQuery在父项上单击事件,但找到子(点击)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆