冒泡事件
就是点击子节点,会向上触发父节点,祖先节点的点击事件。
- 我们在平时的开发过程中,肯定会遇到在一个div(这个div可以是元素)包裹一个div的情况,但是呢,在这两个div上都添加了事件,如果点击里面的div我们希望处理这个div的事件,但是呢,我们不希望外层的div的事件也执行,这时候我们就要用到阻止冒泡。
<style>
#content {
width: 140px;
border: 1px solid blue;
}
#msg {
width: 100px;
height: 100px;
margin: 20px;
border: 1px solid red;
}
</style>
<body>
<div id="content">
外层div
<div id="msg">
内层div
</div>
</div>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(function(){
// 为内层div绑定click事件
$("#msg").click(function(){
alert("我是小div");
});
// 为外层div元素绑定click事件
$("#content").click(function(){
alert("我是大div");
});
// 为body元素绑定click事件
$("body").click(function(){
alert("我是body");
});
});
</script>
</html>
- 当点击小div时,会触发大div与body 的点击事件。点击大div时会触发body的点击事件。



使用阻止冒泡 event.stopPropagation();
<script type="text/javascript">
$(function(){
// 为内层div绑定click事件
$("#msg").click(function(event){
alert("我是小div");
event.stopPropagation(); // 阻止事件冒泡
});
// 为外层div元素绑定click事件
$("#content").click(function(event){
alert("我是大div");
event.stopPropagation(); // 阻止事件冒泡
});
// 为body元素绑定click事件
$("body").click(function(event){
alert("我是body");
event.stopPropagation(); // 阻止事件冒泡
});
});
</script>

还有一种防止默认行为的方法就是return false。效果一样。
<script type="text/javascript">
$(function(){
$("#sub").click(function(event){
//获取元素的值,val() 方法返回或设置被选元素的值。
var username = $("#username").val();
//判断值是否为空
if(username==""){
//提示信息
//alert("文本框的值不能为空");
$("#msg").html("<p>文本框的值不能为空.</p>");
//阻止默认行为 ( 表单提交 )
//event.preventDefault();
return false;
}
});
});
</script>
- 同理,上面的冒泡事件也可以通过return false来处理。
<script type="text/javascript">
$(function(){
// 为内层div绑定click事件
$("#msg").click(function(event){
alert("我是小div");
//event.stopPropagation(); // 阻止事件冒泡
return false;
});
// 为外层div元素绑定click事件
$("#content").click(function(event){
alert("我是大div");
//event.stopPropagation(); // 阻止事件冒泡
return false;
});
// 为body元素绑定click事件
$("body").click(function(event){
alert("我是body");
//event.stopPropagation(); // 阻止事件冒泡
return false;
});
});

提交按钮阻止事件
- 有时候点击提交按钮会有一些默认事件。比如跳转到别的界面。但是如果没有通过验证的话,就不应该跳转。这时候可以通过设置event.preventDefault(); //阻止默认行为 ( 表单提交 )。
<body>
<form action="test.html">
用户名:<input type="text" id="username" />
<br/>
<input type="submit" value="提交" id="sub"/>
<div id="msg"></div>
</form>
</body>
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(function(){
$("#sub").click(function(event){
//获取元素的值,val() 方法返回或设置被选元素的值。
var username = $("#username").val();
//判断值是否为空
if(username==""){
//提示信息
//alert("文本框的值不能为空");
$("#msg").html("<p>文本框的值不能为空.</p>");
//阻止默认行为 ( 表单提交 )
event.preventDefault();
}
});
});
</script>

网友评论