事件冒泡就是当父元素和子元素存在同一事件时在子元素的事件处理程序中会自动调用其父级元素的事件处理程序。
example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>事件冒泡</title>
<script src="jquery-1.8.3.min.js"></script>
<script>
$(function () {
$("#div").click(function () {
$(this).text("我是div");
});
$("#img").click(function () {
$(this).parent().css("border", "1px solid red");
});
})
</script>
</head>
<body>
<div id="div">
<img id="img" src="images/gd.jpg" />
</div>
</body>
</html>
当点击div下的img元素时,div的边框成红色并没有要删除图片,但他在执行子元素(img)的事件处理程序时自动调用了父级元素(div)这就是事件冒泡。
结果:
取消冒泡事件:
事件冒泡是可以由程序员手工取消的也就是在子元素的事件处理程序中手动的停止调用父级元素
example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>事件冒泡</title>
<script src="jquery-1.8.3.min.js"></script>
<script>
$(function () {
$("#div").click(function () {
$(this).text("我是div");
});
$("#img").click(function () {
$(this).parent().css("border", "1px solid red"); event.stopPropagation();
});
})
</script>
</head>
<body>
<div id="div">
<img id="img" src="images/gd.jpg" />
</div>
</body>
</html>