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

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

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


当前回答

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

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

其他回答

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

 $( ".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
})

// if its li get value document.getElementById('li').addEventListener("click", function(e) { if (e.target == this) { UodateNote(e.target.id); } }) function UodateNote(e) { let nt_id = document.createElement("div"); // append container to duc. document.body.appendChild(nt_id); nt_id.id = "hi"; // get conatiner value . nt_id.innerHTML = e; // body... console.log(e); } li{ cursor: pointer; font-weight: bold; font-size: 20px; position: relative; width: 380px; height: 80px; background-color: silver; justify-content: center; align-items: center; text-align: center; margin-top: 0.5cm; border: 2px solid purple; border-radius: 12%;} p{ cursor: text; font-size: 16px; font-weight: normal; display: block; max-width: 370px; max-height: 40px; overflow-x: hidden;} <li id="li"><p>hi</p></li>

定义事件时,该事件具有属性this。此属性表示事件被分配给的DOMElement。要检查触发事件的元素,请使用e.target。

由于事件是在元素的子元素中继承的,因此检查目标是否

function doSomething(event) {
  if (this == event.target){
    // do something
  }
}

如果你不能使用指针事件: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