<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>bubbling event</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="button" value="click" id="button">
</div>
<div id="show">
</div>
</body>
<script>
var n = 0;
$(document).ready(function(){
$("div,#button").click(function(event){
n++;
$("#show").html("The number is :" +n);
})
});
</script>
</html>
可以看见click被执行了2次,阻止冒泡为
var n = 0;
$(document).ready(function(){
$("div,#button").click(function(event){
n++;
$("#show").html("The number is :" +n);
event.stopPropagation(); //阻止冒泡过程
})
});
加上一句就行了。