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

查看:120
本文介绍了按钮里面的div,不发送div onclick - JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,该div有一个onclick事件。在div里面,有一些文字和一个按钮。当我点击文本时,发送div onclick,这很好。但是,当我点击div内的按钮时,会发送按钮的onclick。我知道这是为了发生,但我需要它不会发生。有没有什么办法,没有使用jQuery,当按钮被按下时不发送div onclick?

这是我当前程序的jsFiddle

 < div onclick =divClick()> 
这是div
< button name =testonclick =buttonClick()>点击我< /按钮>
< / div>

我真的不想使用jQuery,只是纯JavaScript p>

解决方案

使用 stopPropagation 事件功能。这样不会调用 divClick 函数。

 函数buttonClick(e ){
if(!e)e = window.event;
e.stopPropagation();
//做你想要的
}

因为Firefox,你需要明确地发送事件作为这样的参数:

 < button name = testonclick =buttonClick(event)>点击我< /按钮> 

演示

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

解决方案

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

这篇关于按钮里面的div,不发送div onclick - JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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