<!DOCTYPE HTML>
<html>
<body>
<style type="text/css">
#a {background-color:blue;width:100px;height:200px;}
#b {background-color:red;margin-left:25px;width:50px;height:100px;}
</style>
<div id="a">a
<div id="b">b</div>
</div>
<script>
document.getElementById("a").onclick = function() {console.log("A is clicked");}
document.getElementById("b").onclick = function(event) {console.log("B is clicked");event.stopPropagation();}
document.onclick = function() {console.log("Document is clicked");}
</script>
</body>
</html>
問題:問題與JS事件冒泡
1. function(event)
,event
是形式參數,什麼是實際參數?實際參數如何傳遞給事件?因爲通常我們用下面的樣式參數:
function method(int num){ //num is the formal
/*implementation*/
}
//in main
method(42); //42 is the actual
- 當我點擊DIV一,在控制檯,它表明:
A is clicked Document is clicked
我想結果應該是
A被點擊
B被點擊
這是我的想法:點擊DIV一個時,document.getElementById("a").onclick
得到excuted,然後document.getElementById("b").onclick
得到excuted,因爲我們有event.stopPropagation();
將在格B停止,並且不會EXCUTE document.onclick
,但似乎不以這種方式工作,任何人都可以幫助我理解這裏發生了什麼?
關於事件的極好的[Quirksmode文章](http://www.quirksmode.org/js/introevents.html)。 – Teemu