<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery事件冒泡和默认行为</title>
<style>
*{
margin: 0;
padding: 0;
}
.father{
width: 200px;
height: 200px;
background-color: #FFEE00;
}
.son{
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script src="jQuery/jquery-1.12.4.js"></script>
<script>
$(function () {
/*
* 1.什么是事件冒泡
* 给标签及上级绑定事件时,标签触发事件同时会触发上级标签的事件
* 如下所示,son属性div为father属性div的子标签。
* son属性的div绑定弹出son弹框的点击事件,
* father属性的div绑定弹出father弹框的点击事件
* 此时我们点击son属性的div,会同时弹出son弹框及father弹框
* */
// $(".son").click(function () {
// alert("son")
// });
// $(".father").click(function () {
// alert("father")
// });
/*
* 2.阻止事件冒泡
* 方法一、return false
* 方法二、函数添加event回调,函数体添加event.stopPropagation()
* 点击son属性的div,不会弹出father弹框
* */
//方法一、return false
// $(".son").click(function () {
// alert("son");
// return false
// });
//方法二、函数添加event回调,函数体添加event.stopPropagation()
$(".son").click(function (event) {
alert("son");
event.stopPropagation();
});
$(".father").click(function () {
alert("father");
});
/*默认行为
* html中有些标签点击后,就有默认行为。比如点击a标签,就会跳转指定连接
* form表单中,点击提交按钮,就会跳转到指定地址
* 阻止默认行为
* 点击a标签只执行jQuery绑定的事件,不执行链接跳转
* 方法一、return false
* // 方法二、函数添加event回调,函数体添加event.preventDefault()
* */
// 给a标签添加点击事件后,点击弹框的确定按钮,就会跳转到百度首页。
// 现在需要点击确定后不进行跳转,此时就要去除a标签的默认事件
// 方法一、return false
$("a").click(function () {
alert("注册");
return false
});
// 方法二、函数添加event回调,函数体添加event.preventDefault()
$("a").click(function (event) {
alert("注册");
event.preventDefault();
})
})
</script>
</head>
<body>
<div class="father">
<div class="son">
</div>
</div>
<a href="https://www.baidu.com/">注册</a>
<form action="https://www.taobao.com/">
<input type="text">
<input type="submit">提交
</form>
</body>
</html>