為什么會冒泡?
<!DOCTYPE html>
<html>
<head>
??? <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
??? <title></title>
??? <style>
??? .left div,
??? .right div {
??????? width: 500px;
??????? height: 100px;
??????? padding: 5px;
??????? margin: 5px;
??????? float: left;
??????? border: 1px solid #ccc;
??? }
?? ?
??? .left div {
??????? background: #bbffaa;
??? }
?? ?
??? .right div {
??????? background: yellow;
??? }
??? </style>
??? <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
??? <h3>事件對象的屬性與方法</h3>
??? <div class="left">
??????? <div id="content">
??????????? 外層div元素
??????????? <br />
??????????? <span style="background: silver;">內(nèi)層span元素</span>
??????????? <br /> 外層div元素
??????? </div>
??????? <br />
??????? <div id="msg"></div>
??? </div>
??? <script type="text/javascript">
??? //為 <span> 元素綁定 click 事件 ?
??? $("span").click(function() {
??????? $("#msg").html($("#msg").html() + "<p>內(nèi)層span元素被單擊</p>");
??? });
??? //為 Id 為 content 的 <div> 元素綁定 click 事件 ?
??? $("#content").click(function(event) {
??????? $("#msg").html($("#msg").html() + "<p>外層div元素被單擊</p>");
??????? event.stopPropagation(); //阻止事件冒泡 ?
??? });
??? //為 <body> 元素綁定 click 事件 ?
??? $("body").click(function() {
??????? $("#msg").html($("#msg").html() + "<p>body元素被單擊</p>");
??? });
??? </script>
</body>
</html>
2016-11-18
冒泡是瀏覽器的屬性,你理解成規(guī)定就好,不阻止的話默認會一級一級往上傳,看#content的click事件函數(shù)里寫了stopPropagation阻止冒泡,所心上一級的body的click才不會被觸發(fā),刪掉這句的話,點擊span后所有的click事件都會被觸發(fā)。