Button inside of div, not to send div onclick - JavaScript(div内的按钮,不发送div onclick - JavaScript)
问题描述
我有一个 div,那个 div 有一个 onclick 事件.在 div 内部,有一些文本和一个按钮.当我点击文本时,会发送 div onclick,这很好.但是,当我单击 div 内的按钮时,会发送按钮 和 的 onclick 按钮.我知道这是注定要发生的,但我需要它不要发生.有没有什么办法,不使用使用jQuery,在按下按钮时不发送div onclick?
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?
这是我当前程序的 jsFiddle
<div onclick="divClick()">
This is the div
<button name="test" onclick="buttonClick()">Click Me</button>
</div>
我真的不想用jQuery,只用纯JavaScript
推荐答案
使用 stopPropagation 事件函数.这样divClick
函数就不会被调用了.
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
}
由于 Firefox,您需要像这样显式发送 event
作为参数:
Because of Firefox you need to explicitly send event
as argument like this:
<button name="test" onclick="buttonClick(event)">Click Me</button>
演示
这篇关于div内的按钮,不发送div onclick - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:div内的按钮,不发送div onclick - JavaScript


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01