是否可以检查点击了哪个"儿童"DIV

Cha*_*ung 3 jquery event-handling

如果我写下如下的监听器,

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

<div class="parent">
    <div class="children1"></div>
    <div class="children2"></div>
    <div class="children3"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

例如,我点击了children2,是否可以检查点击了哪些"儿童"DIV parent

谢谢

T.J*_*der 8

是的,您可以查看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');
});
Run Code Online (Sandbox Code Playgroud)

实例 | 资源

或者,如果您希望在单击其中一个子项时触发处理程序,则可以通过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
});
Run Code Online (Sandbox Code Playgroud)

实例 | 资源

请注意,args的顺序是不同的delegate(我更喜欢清晰度)和on(它似乎是其他人都喜欢的).