javascript 的冒泡事件模型先看代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html οnclick="alert('html')">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var bind_click=function($div,func){
$div.bind('click',function(){
return func();
});
};
bind_click($('#first'),function(){alert('first'); });
bind_click($('#second'),function(){alert('second');});
bind_click($('#third'),function(){alert('third');return false;});
});
</script>
</head>
<body οnclick="alert('body')">
<div id="first" style="background-color:red;height:50px" >
<div id="second" style="background-color:black;height:30px" >
<div id="third" style="background-color:blue;height:10px" >Test</div>
</div>
</div>
</body>
</html>
点击 second 层,在Firefox 中分别显示 second first html body
表明js 在body 标签内部事件是冒泡事件模型,而在body 之外是捕获事件模型
而在IE6中点击second 层 分别显示second first body html 证明全部都是冒泡事件模型;但是在高版本的IE如IE9 显示又是second first html body.开发时一定需要注意IE浏览器的版本
bind_click($('#third'),function(){alert('third');return false;});
return false 可以阻断浏览器的冒泡模型
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html οnclick="alert('html')">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var bind_click=function($div,func){
$div.bind('click',function(){
return func();
});
};
bind_click($('#first'),function(){alert('first'); });
bind_click($('#second'),function(){alert('second');});
bind_click($('#third'),function(){alert('third');return false;});
});
</script>
</head>
<body οnclick="alert('body')">
<div id="first" style="background-color:red;height:50px" >
<div id="second" style="background-color:black;height:30px" >
<div id="third" style="background-color:blue;height:10px" >Test</div>
</div>
</div>
</body>
</html>
点击 second 层,在Firefox 中分别显示 second first html body
表明js 在body 标签内部事件是冒泡事件模型,而在body 之外是捕获事件模型
而在IE6中点击second 层 分别显示second first body html 证明全部都是冒泡事件模型;但是在高版本的IE如IE9 显示又是second first html body.开发时一定需要注意IE浏览器的版本
bind_click($('#third'),function(){alert('third');return false;});
return false 可以阻断浏览器的冒泡模型