单击重叠项目上的事件

时间:2009-11-13 12:14:04

标签: javascript jquery events onclick buttonclick

我有

  • 包含点击事件的表格行
  • 点击事件的
  • 按钮,该按钮位于表格行

我有问题。当我点击按钮时,行点击事件也会执行,但我不想要这种行为。我只希望按钮点击执行,无需点击行。

5 个答案:

答案 0 :(得分:7)

使用jQuery(由于问题标签):

$('#yourButton').click(function(e) {
    // stop event from bubbling up to row element
    e.stopPropagation();

    // now do your stuff
});

答案 1 :(得分:5)

查看您的代码,这是您在按钮点击事件中应该执行的操作 stopPropagation

答案 2 :(得分:3)

您可以在点击

上调用额外的功能

这是函数:

function cancelBubble(e){

    e.cancelBubble = true;
    if(e.stopPropagation)
     e.stopPropagation();
}

按钮的onClick你可以像

一样写
onclick="yourfunctionname();cancelBubble(event)"

yourfunctionname ::是您正在调用的函数的名称。

答案 3 :(得分:1)

另外 我在可点击元素上叠加了一个下拉列表。因此,只需使用以下内容即可防止传播到所有现代浏览器的底层元素

onclick="yourfunctiontohandle();event.stopPropagation();"

对于较旧的跨浏览器解决方案,必须使用IE event.cancelBubble

onclick="if(event.stopPropagation) event.stopPropagation(); else event.cancelBubble=true;"

答案 4 :(得分:0)

由于不推荐使用全局事件,如果有人想使用纯 javascript,这里是停止传播的方法

document.querySelector("#outer").addEventListener('click', e => {console.log('Outer div clicked')});
document.querySelector("#inner").addEventListener('click', e => {console.log('Inner div clicked'); e.stopPropagation()});
<div id="outer" style="width: 100px; height: 100px; background-color: red; display: flex; justify-content: center; align-items: center;">
    <div id="inner" style="background-color: black; width: 50px; height: 50px;"></div>
</div>

点击红色和黑色方块查看结果