jQuery中事件冒泡问题及处理

在为一个元素添加事件时,经常会出现的一个问题就是事件冒泡。例如在div中嵌套了一个span元素,为div和span都添加了事件点击,如果点击span会导致span和div元素相继触发监听事件。顺序是从内到外。代码如下:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>事件冒泡演示</title>
<meta name="author" content="Administrator" />
<script src="script/jquery-1.12.2.js" type="text/javascript"></script>
<style type="text/css">
#content {
background-color: #0000FF;
}
#msg {
background-color: #FF0000;
}
</style>
<!-- Date: 2016-03-26 -->
</head>
<body>
<div id="content">
<p>
外层div元素
</p>
<span>内层span元素</span>
<p>
外层div元素
</p>
</div>
<div id="msg"></div>
<script type="text/javascript">
$(function() {
//对span元素添加事件
$("#content span").bind("click", function() {
var text = $("#msg").html()+"<p>内层span元素被点击!</p>";
$("#msg").html(text);
});
//对
$("#content").bind("click", function() {
var text = $("#msg").html()+"<p>外层div元素被点击!</p>";
$("#msg").html(text);
}); $("body").bind("click", function() {
var text = $("#msg").html()+"<p>body元素被点击!</p>";
$("#msg").html(text);
});
});
</script>
</body>
</html>

为了更好地解决这个问题,我们为事件中的function传入一个参数event,并且调用stopPropagation()方法

下面演示:

 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>事件冒泡演示</title>
<meta name="author" content="Administrator" />
<script src="script/jquery-1.12.2.js" type="text/javascript"></script>
<style type="text/css">
#content {
background-color: #0000FF;
}
#msg {
background-color: #FF0000;
}
</style>
<!-- Date: 2016-03-26 -->
</head>
<body>
<div id="content">
<p>
外层div元素
</p>
<span>内层span元素</span>
<p>
外层div元素
</p>
</div>
<div id="msg"></div>
<script type="text/javascript">
$(function() {
//对span元素添加事件
$("#content span").bind("click", function(event) {
var text = $("#msg").html()+"<p>内层span元素被点击!</p>";
$("#msg").html(text);
event.stopPropagation();
});
//对
$("#content").bind("click", function(event) {
var text = $("#msg").html()+"<p>外层div元素被点击!</p>";
$("#msg").html(text);
event.stopPropagation();
}); $("body").bind("click", function(event) {
var text = $("#msg").html()+"<p>body元素被点击!</p>";
$("#msg").html(text);
event.stopPropagation();
});
});
</script>
</body>
</html>
上一篇:Linux实战教学笔记07:Linux系统目录结构介绍


下一篇:暑期训练狂刷系列——Hdu 1698 Just a Hook (线段树区间更新)