单击父级,忽略其子级

gub*_*ett 5 javascript jquery dom

可能重复:
jQuery:单击函数排除子项.

我有两个div,像这样:

<div id="parent" style="width: 100%; height: 100%; background-color:red;" />
    <h1>I'm the parent!</h1>
    <div id="child" style="width: 300px; height: 200px; background-color:yellow;">
        </h2>..and I'm the child!</h2>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

另外,我有以下JavaScript代码:

$(document).ready(function(){
    $('#parent').click(function(){
        alert('Parent was clicked');
    });
});
Run Code Online (Sandbox Code Playgroud)

问题是,如果我点击孩子,就会触发事件.如何才能将此事件限制为仅限父母?

编辑:只是为了澄清; 我希望当用户点击红色的任何地方时触发此操作.正如评论中所说; 该h1不是父.Tjirp的答案就是诀窍,而且这个解决方案的答案很多.

Tji*_*irp 12

这应该工作

$(document).ready(function() {
    $('#parent').click(function(e) {
        if (e.target == this) { 
            alert('Parent was clicked');
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样您就不必将任何东西绑定到您的孩子身上.click事件将传播到您的click处理程序,并检查click事件的目标是否确实是您添加事件的元素.

编辑:我是对的.这不是最有效的方式,Alessandro Minoccheri的回答应该更快.我用他的代码更新了我的代码.


Ale*_*eri 5

试试这个:

$('#parent').click(function(data, handler){
  if (data.target == this) {
    //Do Stuff (only element clicked, not children)
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 参数名称的奇怪选择,考虑到你所谓的"数据"实际上是事件. (4认同)