Button inside of div, not to send div onclick - Ja

2020-03-26 12:44发布

问题:

I have a div, and that div has an onclick event. Inside of the div, there is some text, and a button. When I click on the text, the div onclick is sent, which is good. However, when I click in the button inside of the div, the onclick for the button and the div are sent. I know that this is meant to happen, but I need it to not happen. Is there any way, without using jQuery, to not send off the div onclick, when the button is pressed?

Here is a jsFiddle of my current program

<div onclick="divClick()">
This is the div
<button name="test" onclick="buttonClick()">Click Me</button>
</div>

I really do not want to use jQuery, just pure JavaScript

回答1:

Use stopPropagation event function. This way divClick function will not be called.

function buttonClick(e) {
   if (!e) e = window.event;
   e.stopPropagation();
   // do what you want
}

Because of Firefox you need to explicitly send event as argument like this:

<button name="test" onclick="buttonClick(event)">Click Me</button>

Demo