在使用jquery进行事件处理的时候,当从里到外的多层都响应某一事件,然后又在里层发生该事件时,jquery默认是会从里到外依次响应各个事件的,然而有时候这并不是我们所需要的。这个时候就需要我们来阻止外层事件的发生,阻止冒泡。
jquery中可以用来阻止事件冒泡的主要有两种,stopPropagation()和return false
如:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<style type="text/css">
#inner {
height: 100px;
background: #cfc;
}
#middler {
background: #ccf;
}
#outer {
background: #fcc;
}
div {
border: 1px solid blue;
padding: 20px;
width: 200px;
}
</style>
<script type="text/javascript" src="/tiantian/js/jquery-1.5.js"></script>
<script type="text/javascript">
$(function() {
$("div").click(function(event) {
alert($(this).attr("id"));//这样在点击inner的时候会从里到外依次响应其点击事件,依此弹出inner,middler,outer
//return false;//这样则会阻止其默认行为,阻止事件不再冒泡,这样就只会弹出inner
event.stopPropagation();//阻止事件冒泡
});
});
</script>
</head>
<body>
<div id="outer">
最外层
<div id="middler">
中间层
<div id="inner">最里层</div>
</div>
</div>
</body>
</html>