我目前使用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>

当前回答

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

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

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

});

其他回答

这就是你要找的

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

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

   // do stuff
}

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

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

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

内联选择:

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

你也可以试试这个

$("#clickable").click(function(event) {
    var senderElementName = event.target.tagName.toLowerCase();
    if(senderElementName === 'div') {
        // Do something here 
    } else {
        // Do something with <a> tag
    }
});
<a onclick="return false;" href="http://foo.example">I want to ignore my parent's onclick event.</a>

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

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