假设我有一个父元素,它本身有很多嵌套的子元素:
<div id="p">
<div id="c1">
<div id="c2"></div>
<div id="c3"></div>
</div id="c4">
<div id="c5"></div>
</div>
</div>
我已经在父级上绑定(bind)了一个 click
事件:
$('#p').bind('click', function() {
alert($(this).attr('id'));
});
因为事件是分配给父元素的,所以我总是看到父元素,但是,我想知道是否有任何可能的方法来找出这个子元素中的哪些被点击了?
我也无法将任何事件分配给子元素或从父 div 中删除事件监听器。
最佳答案
您需要将事件对象传递给函数以获取触发事件的项目,event.target 将为您提供源元素。
$('#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')
。
关于javascript - 父级上的 jQuery 单击事件,但找到子(单击)元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12758547/