jQuery防止在触发子事件时触发父事件

时间:2013-01-23 11:12:09

标签: jquery element parent

最近我遇到了一些jQuery问题。我们只是说我有这样的元素:

<div id="parent1" class="parent">
    <div id="child1" class="children">
        <a href="" id="child_link1" class="child_link"></a>
    </div>
</div>

我有这样的jQuery函数:

$(".parent").click(function(){
    alert("parent is clicked");
});

$(".child_link").click(function(){
    alert("child link is clicked");
});

如果单击child_link,也会触发父级。我如何创建一种情况,如果我点击child_link,父母不会被触发?

3 个答案:

答案 0 :(得分:9)

您需要在子点击事件上停止传播,如下所示:

$(".child_link").click(function(e) {
    e.stopPropagation();
    alert("child link is clicked");
});

Example fiddle

答案 1 :(得分:4)

孩子的事件处理程序应该这样写:

$(".child_link").click(function( event ){
    event.stopPropagation();
    alert("child link is clicked");
});

这将停止event bubbling,并且不会调用父级的事件处理程序。

答案 2 :(得分:4)

看到你的活动正在冒泡到它的父母。所以在这里你必须使用.stopPropagation();

$(".child_link").click(function(ev){
  ev.stopPropagation(); //<----------------this stops the event to bubble up
  alert("child link is clicked");
});
相关问题