gpt4 book ai didi

jquery - 是否可以检查哪个 "children"DIV被点击

转载 作者:行者123 更新时间:2023-12-01 00:40:51 25 4
gpt4 key购买 nike

如果我按如下方式编写监听器,

$('.parent').bind('click', function() {
//...
})

<div class="parent">
<div class="children1"></div>
<div class="children2"></div>
<div class="children3"></div>
</div>

例如我点击了children2,是否可以检查parent下的哪个“children”DIV被点击了?

谢谢

最佳答案

是的,您可以查看e.target(更改您的处理程序以接受e作为参数),可能使用closest获取单击的实际元素的第一个 div 祖先(如果这些子 div 有后代)。

$('.parent').bind('click', function(e) {
// Here, `e.target` is the DOM element where the click occurred
var div = $(e.target).closest('div');
});

Live Example | Source

或者,如果您希望在单击其中一个子项时触发处理程序,则可以通过 delegate 使用事件委托(delegate)或on :

$('.parent').delegate('div', 'click', function(e) {
// Here, `this` is the child div that was clicked
});

// or

$('.parent').on('click', 'div', function(e) {
// Here, `this` is the child div that was clicked
});

Live Example | Source

请注意,delegate(为了清晰起见,我更喜欢这种方式)和 on(似乎其他人都更喜欢这种方式)之间的参数顺序是不同的。

关于jquery - 是否可以检查哪个 "children"DIV被点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15173892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com