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

当前回答

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

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

其他回答

如果在任何情况下都不打算与内部元素交互,那么CSS解决方案可能对您有用。

只需将内部元素/s设置为pointer-events: none

在你的情况下:

.clickable > a {
    pointer-events: none;
}

或笼统地针对所有内部元素:

.clickable * {
    pointer-events: none;
}

这个简单的hack在用ReactJS开发时为我节省了很多时间

浏览器支持可以在这里找到:http://caniuse.com/#feat=pointer-events

所有的解决方案是复杂的和jscript。下面是最简单的版本:

var IsChildWindow=false;

function ParentClick()
{
    if(IsChildWindow==true)
    {
        IsChildWindow==false;
        return;
    }
    //do ur work here   
}


function ChildClick()
{
    IsChildWindow=true;
    //Do ur work here    
}

这就是你要找的

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

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

   // do stuff
}

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

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

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

如果单击子元素,则事件将弹出到父元素和事件。== event. currentarget。

所以在你的函数中,你可以检查这个并提前返回,即:

var url = $("#clickable a").attr("href");
$("#clickable").click(function(event) {
    if ( event.target !== event.currentTarget ){
        // user clicked on a child and we ignore that
        return;
    }
    window.location = url;
    return true;
})

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

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

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