我有一个div,我已经附加了一个onclick事件。在这个div中有一个带有链接的标签。当我点击链接时,来自div的onclick事件也被触发。我怎么能禁用这一点,如果链接被点击在div onclick不被解雇?

脚本:

$(document).ready(function(){
    $(".header").bind("click", function(){
         $(this).children(".children").toggle();
    });
})

html代码:

<div class="header">
    <a href="link.html">some link</a>
    <ul class="children">
        <li>some list</li>
    </ul>
</div>

当前回答

或:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        return false;
   });
});

其他回答

我无意中发现了这个问题,在寻找另一个答案。

我想防止所有子节点触发父节点。

JavaScript:

document.getElementById("parent").addEventListener("click", function (e) {
    if (this !== event.target) return;
    // Do something
});

jQuery:

$("#parent").click(function () {
    // Do something
}).children().on("click", function (e) {
    e.stopPropagation();
});

这样做:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        e.stopPropagation();
   });
});

如果您想阅读有关. stoppropagation()的更多信息,请查看这里。

或:

$(document).ready(function(){
    $(".header").click(function(){
        $(this).children(".children").toggle();
    });
   $(".header a").click(function(e) {
        return false;
   });
});

最简单的解决方案是将CSS添加到子节点:

.your-child {
    pointer-events: none;
}

更好的方法是使用on()和链接,

$(document).ready(function(){
    $(".header").on('click',function(){
        $(this).children(".children").toggle();
    }).on('click','a',function(e) {
        e.stopPropagation();
   });
});