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
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07