【问题标题】:Button in a div both with onclick event - how to trigger only one of both when clicking onto the button?div中的按钮都带有onclick事件-单击按钮时如何仅触发两者之一?
【发布时间】:2014-08-20 22:05:05
【问题描述】:

我正在尝试创建一个内部带有按钮的 div,如下所示:

<div onclick="function()"><input onclick="otherfunction()" type="button"></div>

如果您单击按钮,则会触发两个事件,但我只想在您点击按钮时触发按钮的事件。 我尝试更改按钮的 z-index 以使其超过 div,但这没有帮助。

有没有办法解决这个问题?

感谢您的回答, 丹尼尔

P.S.:很抱歉有任何拼写或语法错误,这不是我的母语。

【问题讨论】:

  • 您能否更具体地说明您要在这里实现的目标。点击dig时应该发生什么,点击按钮时应该发生什么?
  • 我假设你的 div 是一个大正方形或其他东西,而按钮在那个正方形里面,对吧?

标签: javascript jquery html button onclick


【解决方案1】:

需要使用“stopPropagation”停止冒泡。试试这个:

<script>
    var test = function() {
        alert(2);
        event.stopPropagation();
    };
</script>

<div onclick="alert(1)"><input onclick="test()" type="button"></div>

【讨论】:

    【解决方案2】:

    您想停止传播,请使用提供的事件对象。出于说明目的,我按标签名称进行选择,但您也提供了 id。请注意,IE 直到版本 9 才支持 ent.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 */
    }
    

    jsfiddle

    【讨论】:

      猜你喜欢
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 1970-01-01
      相关资源
      最近更新 更多