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
基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
