我有一个DIV与一个分类的foobar,和一些DIV内的DIV是未分类的,但我认为他们继承了foobar类:

$('.foobar').on('click', function() { /*...do stuff...*/ });

我希望它只在点击DIV的某个地方时发射,而不是在它的子DIV上。


当前回答

我有同样的问题,并提出了这个解决方案(基于其他答案)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

基本上,如果目标是div则运行代码否则什么都不做(不要隐藏它)

其他回答

$(".advanced ul li").live('click',function(e){
    if(e.target != this) return;
    //code
    // this code will execute only when you click to li and not to a child
})
//bind `click` event handler to the `.foobar` element(s) to do work,
//then find the children of all the `.foobar` element(s)
//and bind a `click` event handler to them that stops the propagation of the event
$('.foobar').on('click', function () { ... }).children().on('click', function (event) {
    event.stopPropagation();
    //you can also use `return false;` which is the same as `event.preventDefault()` and `event.stopPropagation()` all in one (in a jQuery event handler)
});

这将停止点击事件在.foobar元素的任何子元素上的传播(冒泡),因此事件不会到达.foobar元素以触发它们的事件处理程序。

这里是一个演示:http://jsfiddle.net/bQQJP/

如果e.target与这个元素相同,则没有单击后代。

$ (' .foobar ')。On ('click',函数(e) { If (e.target !== this) 返回; Alert('点击foobar'); }); .foobar { 填充:20 px;背景:黄色; } 跨度{ 背景:蓝色;颜色:白色;填充:8 px; } < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js " > < /脚本> <div class='foobar'> .foobar (alert) <span>child (no alert)</span> < / div >

你可以使用event. currentarget。它只会点击得到事件的元素。

目标= e => 控制台日志(e . currentTarget); 的; <ul onClick={target}类 < li > < p > <i类 < / p > < / li > < /德>

我没有得到工作的公认答案,但这似乎做的把戏,至少在香草JS。

if(e.target !== e.currentTarget) return;