javascript 带有onclick事件的div中的按钮-单击按钮时如何仅触发两者之一?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25415212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Button in a div both with onclick event - how to trigger only one of both when clicking onto the button?
提问by Daniel
I'm trying to create a div with a button inside, like this:
我正在尝试创建一个带有按钮的 div,如下所示:
<div onclick="function()"><input onclick="otherfunction()" type="button"></div>
If you click the button both events are triggered, but I want to only trigger the event of the button if you hit it. I tried to change the z-index of the button to get it over the div but that didn't help.
如果您单击按钮,两个事件都会被触发,但我只想在您点击按钮时触发该事件。我试图更改按钮的 z-index 以使其越过 div,但这没有帮助。
Is there any posibility to approach that?
有没有可能解决这个问题?
Appreciating your answers, daniel
感谢您的回答,丹尼尔
P.S.: Sorry for any spelling or grammar mistakes this is not my first language.
PS:抱歉任何拼写或语法错误,这不是我的母语。
回答by Mark Estrada
Need to stop bubbling with 'stopPropagation'. Try this:
需要用“stopPropagation”停止冒泡。试试这个:
<script>
var test = function() {
alert(2);
event.stopPropagation();
};
</script>
<div onclick="alert(1)"><input onclick="test()" type="button"></div>
回答by ron tornambe
You want to stop propagation use the supplied event object. I am selecting by tag name for illustration purposes, but you supply id's as well. Note that eent.stopPropagation is not supported by IE until version 9:
您想使用提供的事件对象停止传播。出于说明目的,我按标签名称进行选择,但您也提供了 id。请注意,IE 直到版本 9 才支持 eent.stopPropagation:
<div)>
<input type="button" />
</div>
document.getElementsByTagName('div')[0].onclick = function(e) {
alert('div clicked');
e.stopPropagation()
/* do something */
}
document.getElementsByTagName('input')[0].onclick = function(e) {
alert('button clicked');
e.stopPropagation()
/* do something */
}