简体   繁体   中英

How can I know event reach which element?

my html structure like this below:

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

$('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

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

in 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(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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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