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

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

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


当前回答

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

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

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

其他回答

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

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

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

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

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

我的情况类似,但这是当你有几个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'
});

如果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 >

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