如果嵌套元素触发事件,请不要让容器处理该事件 [英] If a nested element fires an event, dont let the container handle it
本文介绍了如果嵌套元素触发事件,请不要让容器处理该事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含另一个div的div. 如果用户单击内部div,则仅希望执行附加到此元素的事件处理程序.现在,首先执行内部元素的事件处理程序,然后执行外部元素的事件处理程序.有办法改变吗?
I have a div that contains another div. If the user clicks the inner div I only want the eventhandler attached to this element get executed. Right now first the eventhandler of the inner element and then that of the outer element gets executed. Is there a way to change this?
<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>
推荐答案
您可以停止传播:
$("#innerElement").click(function(event){
alert("This comes from inner element");
event.stopPropagation();
});
这篇关于如果嵌套元素触发事件,请不要让容器处理该事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文