阻止Bootstrap删除按钮点击传播

Preventing Bootstrap delete button click from propagating

本文关键字:传播 按钮 Bootstrap 删除 阻止      更新时间:2023-09-26

如何防止点击从删除按钮传播?我使用Twitter Bootstrap 3来显示图像旋转木马,可以选择单击并在模式对话框中显示全尺寸图像,该对话框由幻灯片分区上的onclick触发。

问题是,我还试图在幻灯片div中包含一个删除按钮,点击从删除按钮传播到包含的div,这意味着当你试图删除时,它会弹出CakePHP"你确定吗?"消息,如果你说不,模态会打开。

为什么stopPropagation()不在这里工作?

<div class="item" onclick="$('show-image').modal('show');" style="background-image:url(blablabla);">
    <div class="carousel-caption" onclick="function handler(event) {event.stopPropagation();}">
    Image caption goes here
    CakePHP framework Javascript delete button goes here (generated in PHP)
    </div>
</div>

您的onclick实际上并没有使用您在其中定义的函数。您可以让它像这样工作(在IE9+和其他现代浏览器上):

onclick="event.stopPropagation();"

请注意,这不是函数,而是函数的内容

DOM0 onXyz处理程序本质上可以归结为:

theElement.onclick = function(event) {
    // ...your onclick content here
};

所以你可以看到为什么你的代码不起作用:

theElement.onclick = function(event) {
    function handler(event) {event.stopPropagation();}
};

但是,当您使用jQuery时,最好不要使用onXyz属性,而是以现代方式连接处理程序:

$(".carousel-caption").on("click", function(e) {
    e.stopPropagation();
    // do your thing here
});

stopPropagation在代码中不起作用的原因是onclick="function(e){}"什么都不做,它只是声明了一个函数并将其丢弃。

以下是您想要的通用解决方案:

<div class="parent" onclick="parentClicked();">
    <div class="child" onclick="event.stopPropagation();childClicked();">
    </div>
</div>

window.event被设置为正在激发的当前事件,在本例中为MouseEvent对象。