[英]Javascript Event Delegation issue with target
I have this HTML (example): 我有这个HTML(示例):
<div class="a">
<div class="b">
<img src="...">
<p>text</p>
</div>
<div class="b">
<img src="...">
<p>text</p>
</div>
<div class="b">
<img src="...">
<p>text</p>
</div>
</div>
And I have like, 1000 of the div.b
. 我喜欢
div.b
1000。 I need to add event listener to div.a
and target the div.b
children. 我需要将事件侦听器添加到
div.a
并定位div.b
子级。
However the event.target
may also be img
, or p
: 但是
event.target
也可以是img
或p
:
document.querySelector('.a').addEventListener('click', handler);
function handler(e){
console.log(e.target); //either .b or img or p depending on where I click
}
I need something like this (jQuery): 我需要这样的东西(jQuery):
$('.a').on('click', '.b', function(){
//code
});
You can extend your query selector like in css file, to select the children of class. 您可以像在css文件中一样扩展查询选择器,以选择类的子级。
The following code tested on clicking the search bar on SO. 以下代码在单击SO上的搜索栏时进行了测试。 you can try it on console
您可以在控制台上尝试
document.querySelector('.top-bar .f-input').addEventListener('click', function(e){
console.log(e)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.