我目前使用jQuery使一个div可点击,在这个div我也有锚。我遇到的问题是,当我点击一个锚都点击事件是发射(div和锚)。我如何防止div的onclick事件从发射时,一个锚被单击?

下面是破碎的代码:

JavaScript

var url = $("#clickable a").attr("href");

$("#clickable").click(function() {
    window.location = url;
    return true;
})

HTML

<div id="clickable">
    <!-- Other content. -->
    <a href="http://foo.example">I don't want #clickable to handle this click event.</a>
</div>

当前回答

这就是你要找的

mousedown事件。这适用于每个DOM元素,以防止javascript的焦点处理程序,像这样:

$('.no-focus').mousedown(function (e) {
   e.prevenDefault()

   // do stuff
}

在vue.js框架中,你可以这样使用修饰符:

<span @mousedown.prevent> no focus </span>

注意,使用on输入将阻止文本选择处理程序

其他回答

和ev比较。当这个不可用时(React等)。

$("#clickable").click(function(e) {
    if (e.target === e.currentTarget) {
        window.location = url;
        return true;
    }
})

如果它在内联上下文中,在HTML中尝试这样做:

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

这里是我的解决方案,每个人都在寻找一个非jquery代码(纯javascript)

document.getElementById("clickable").addEventListener("click", function(e) {
    e = window.event || e; 
    if(this === e.target) {
      // put your code here
    }
});

如果点击父级的子级,你的代码将不会被执行

e.s stoppropagation()是一个正确的解决方案,但如果你不想在你的内部锚上附加任何事件处理程序,你可以简单地将这个处理程序附加到你的外部div:

e => { e.target === e.currentTarget && window.location = URL; }

要指定某些子元素为不可点击的,请按照下面的示例编写css层次结构。

在这个例子中,我停止传播到一个类为".subtable"的表中td和tr中的任何元素(*)

$(document).ready(function()
{    
   $(".subtable tr td *").click(function (event)
   {
       event.stopPropagation();
   });

});