实例代码“Ctrl+/”提示“F11/ESC”全屏 返回 格式化 恢复 运行
x
 
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script src="https://libs.baidu.com/jquery/1.10.2/jquery.min.js">
5
</script>
6
<script>
7
$(document).ready(function(){
8
  $("span").click(function(event){
9
    event.stopPropagation();
10
    alert("The span element was clicked.");
11
  });
12
  $("p").click(function(event){
13
    alert("The p element was clicked.");
14
  });
15
  $("div").click(function(){
16
    alert("The div element was clicked.");
17
  });
18
});
19
</script>
20
</head>
21
<body>
22
23
<div style="height:100px;width:500px;padding:10px;border:1px solid blue;background-color:lightblue;">
24
This is a div element.
25
<p style="background-color:pink">This is a p element, in the div element. <br><span style="background-color:orange">This is a span element in the p and the div element.</span></p></div>
26
27
<p><b>Note:</b> Click on each of the elements above. When clicking on the <b>div</b> element, it will alert that the div element was clicked. When clicking on the <b>p</b> element, it will return both the p and the div element, since the p element is inside the div element. 
28
But when clicking on the <b>span</b> element, it will only return itself, and not the p and the div element (even though its inside these elements).  The event.stopPropagation() stops the click event from bubbling to the parent elements. 
29
</p>
30
<p><b>Tip:</b> Try to remove the event.stopPropagation() line, and click on the span element again (the click event will now bubble up to parent elements).</p>
31
32
</body>
33
</html>