div内的按钮,不发送div onclick - JavaScript [英] Button inside of div, not to send div onclick - JavaScript

查看:29
本文介绍了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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆