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
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>
来源:https://stackoverflow.com/questions/18833696/button-inside-of-div-not-to-send-div-onclick-javascript