2013-01-23 200 views
5

最近我遇到了一些jQuery问题。让我们只说我有内容是这样的: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,父母不会被触发?

回答

9

你需要停止对孩子点击事件传播,如:

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

Example fiddle

+0

感谢您的答复,我尝试使用stopPropagation但遗憾的是,并没有引发连child_link事件。它只返回到首页无所事事。 –

+0

您是否记得将事件传递给函数? '.click(function(e){'< - there –

4

为孩子的事件处理函数应该这样写这样:

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

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

+0

感谢您的回复,我尝试过使用stopPropagation,但不幸的是,即使child_link事件没有被触发,它只返回首页无所作为。 –

4

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

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

原因downvote?plz share。 – Jai

+1

我不知道是谁投了票,我投了票给你补偿:) –

+1

你也值得。:) – Jai