2012-02-09 57 views
0

我有一个包含另一个div的div。 如果用户点击内部div,我只希望附加到这个元素的eventhandler得到执行。现在先是内部元素的事件处理程序,然后执行外部元素的事件处理程序。有没有办法改变这个?如果嵌套元素触发事件,不要让容器处理它

<html> 
    <head> 
    <meta charset="utf-8"> 
    <title>Demo</title> 
    </head> 
    <body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     $("#containerElement").click(function(event){ 
     alert("This comes from container"); 
     }); 

     $("#innerElement").click(function(event){ 
     alert("This comes from inner element"); 
     }); 
    }); 
    </script> 


    <div id="containerElement" > 
    This is the container 
    <div id="innerElement" > 
    This is the inner element 


    </div> 

    </div> 
    </body> 
</html> 
+0

太简单的问题似乎。 2分钟和4个几乎完全相同的答案^^ – raphinesse 2012-02-09 22:51:08

回答

2

你可以stop the propagation

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
+0

这很好用! – 2012-02-09 23:22:02

0

event.stopPropagation()添加到您的innerElement事件处理函数中。有关更多信息,请参阅jQuery docs

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
+0

给予最低代表代表的荣誉! XD – raphinesse 2012-02-09 22:52:50

1

添加event.stopPropagation();

$("#innerElement").click(function(event){ 
    alert("This comes from inner element"); 
    event.stopPropagation(); 
}); 
1

从处理程序返回false将防止起泡(除其他事项外):

$("#innerElement").click(function(event){ 
    alert("This comes from container"); 
    return false; 
}); 
+0

您是否想要将'return false;'添加到'#innerElement'?您的代码仍然会触发包含元素的点击事件。 – 2012-02-09 22:49:46

+0

@科林..感谢 – paislee 2012-02-09 22:50:23