<!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>
问题:
1.function(event)
,event
是形参,什么是实参?实际参数如何传递给事件?因为通常我们使用以下样式的参数:
function method(int num){ //num is the formal
/*implementation*/
}
//in main
method(42); //42 is the actual
- 当我点击 div a 时,在控制台中显示:
A is clicked Document is clicked
我以为结果应该是
A is clicked
B is clicked
这是我的想法:当点击 div a 时,document.getElementById("a").onclick
被执行,然后 document.getElementById("b").onclick
被执行了,因为我们有 event.stopPropagation();
它会在 div b 中停止,并且不会执行 document.onclick
,但它似乎不能这样工作,谁能帮我了解这里发生了什么?
最佳答案
function(event)
,event
is formal parameter, what is the actual parameter?
实参是一个事件对象,由浏览器创建。对于点击事件,它将是 MouseEvent
的一个实例.
when I clicked div a... I thought the result should be...
您单击了 b
的父级。该事件从目标向上传播 DOM 树,因此它永远不会触及 b
。传播阶段将从 a
开始,向上移动通过每个父级,直到它到达文档。
如果您点击了 b
,stopPropagation
方法会阻止事件冒泡,您只会在输出中看到“B is clicked”。
关于javascript - js中的事件冒泡问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17339856/