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

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

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


当前回答

如果你不能使用指针事件:none;并且针对现代浏览器,你可以使用composedPath来检测对对象的直接点击,如下所示:

element.addEventListener("click", function (ev) {
    if (ev.composedPath()[0] === this) {
        // your code here ...
    }
})

你可以在这里阅读关于composedPath的更多信息: https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath

其他回答

你可以用冒泡来帮助自己:

$('.foobar').on('click', function(e) {
    // do your thing.
}).on('click', 'div', function(e) {
    // clicked on descendant div
    e.stopPropagation();
});
$(".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
})

我的情况类似,但这是当你有几个foobar-s,你想关闭只有一个-每次点击:

查找父case

$(".foobar-close-button-class").on("click", function () {
    $(this).parents('.foobar').fadeOut( 100 );
    // 'this' - means that you finding some parent class from '.foobar-close-button-class'
    // '.parents' -means that you finding parent class with name '.foobar'
});

查找子案例

$(".foobar-close-button-class").on("click", function () {
    $(this).child('.foobar-close-button-child-class').fadeOut( 100 );
    // 'this' - means that you finding some child class from '.foobar-close-button-class'
    // '.child' -means that you finding child class with name '.foobar-close-button-child-class'
});

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

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

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

//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/