简体   繁体   English

我怎么知道事件到达哪个元素?

[英]How can I know event reach which element?

my html structure like this below: 我的html结构如下:

<div onclick='g(e)'>
    <span><button>click me</button></span>
</div>

when I click the button tag,the click event will deliver to the div.So my question is when the click event deliver to the span element,if some condition is true,then I can call e.stopPropagation(),and it will not deliver to the div element,the function g wil not run.Would you like to help me?Thanks. 当我单击button标记时,click事件将传递到div。所以我的问题是,将click事件传递到span元素时,如果满足某些条件,则可以调用e.stopPropagation(),但不会传递给div元素,函数g将无法运行。您想帮助我吗?谢谢。

$('span').click(function(e){if(true){e.stopPropagation();e.preventDefault()};});

you can try it but in your case it always come on button 您可以尝试一下,但是在您的情况下,它总是在按钮上

IN HTML 在HTML中

<div rel="div">
    <span rel="span"><button>click me</button></span>
</div>

in JS 在JS中

$("button").click(function(e){
   console.log(e.target);
if($(e.target).attr("rel")=="span")
{
e.stopPropagation();
    alert("click on span");
    //f(e);
}
else if($(e.target).attr("rel")=="div"){
alert("click on div");

}
  else{
      alert("click on button");
    }

});

see demo 观看演示

or you want to your work then apply click action on div in this span ,button and div come like below 或者您想要工作,然后在此范围内对div应用click操作,按钮和div如下所示

$("div").click(function(e){
   console.log(e.target);
if($(e.target).attr("rel")=="span")
{
e.stopPropagation();
    alert("click on span");
    //f(e);
}
else if($(e.target).attr("rel")=="div"){
alert("click on div");

}
  else{
      alert("click on button");
    }

}); 

see demo 观看演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM