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

自闭症网瘾萝莉.ら 提交于 2019-12-01 07:31:02

问题


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



来源:https://stackoverflow.com/questions/18833696/button-inside-of-div-not-to-send-div-onclick-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!