如果嵌套元素触发了一个事件,不要让容器处理它
If a nested element fires an event, dont let the container handle it
我有一个包含另一个div的div。如果用户单击内部div,我只希望执行附加到该元素的事件处理程序。现在首先执行内部元素的事件处理程序,然后执行外部元素的事件处理器。有办法改变这种情况吗?
<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();
});
添加event.stopPropagation();
$("#innerElement").click(function(event){
alert("This comes from inner element");
event.stopPropagation();
});
从处理程序返回false
将防止冒泡(除其他外):
$("#innerElement").click(function(event){
alert("This comes from container");
return false;
});
将event.stopPropagation()
添加到您的innerElement事件处理程序中。有关更多信息,请参阅jQuery文档。
$("#innerElement").click(function(event){
alert("This comes from inner element");
event.stopPropagation();
});
如上所述:
http://jsbin.com/avikol/2/
相关文章:
- keyup事件处理程序更改焦点不适用于快速键入
- 提示使用服务器端事件处理程序激活JavaScript
- 将事件处理程序绑定到任何可能的事件
- 正在将事件处理程序添加到不存在的类
- dropdown.js中的复杂事件处理
- 在循环中附加事件处理程序时出现浏览器性能问题
- 在同一个javascript事件处理程序中调用不同的函数
- 复选框,然后单击事件处理
- 有没有一种方法可以让内联事件处理程序在元素创建后立即执行
- 检查事件处理程序参数
- 实现延迟的jquery更改事件处理程序
- 如何使用Node.js在JavaScript模块文件之间使用事件处理程序
- 如何使jQuery的“bind”或“on”事件处理程序幂等
- 带有参数的Javascript事件处理程序
- Jquery事件处理程序仅适用于匿名函数
- 如何从另一个处理程序内部取消JavaScript事件处理程序函数的执行
- 如何在 JavaScript 代码中调试点击事件处理
- 如何在jQuery事件处理程序中存储和重用超时
- 如何向onClick事件处理程序传递一个接受参数的函数,并且仍然将该函数绑定到组件's”;这个“;上下文
- 异步处理所有事件处理程序的方法