js 事件捕獲與事件冒泡例子

http://codepen.io/huashiyiqike/pen/qZVdagjavascript

addEventListener 默認是冒泡階段執行,也就是父親與子都監聽時,點擊子,子先處理,父親再處理,這時加stopPropagation()能夠阻止父親的處理事件。設置true反過來,這時加了stopPropagation()能夠阻止子的處理事件。html

jquery 只支持冒泡。java

<html>
<body id="myid2" class="mystyle your">
 <div id="myid"> father
  <div class="2"> son</div>
  </div>
  

<div id="jmyid"> jqueryfather
<div class="j2"> jqueryson</div>
</div>jquery

<script type="text/javascript">

document.getElementById("myid").addEventListener("click",function(e){alert("father called"); },true);
document.getElementsByClassName("2")[0].addEventListener("click",function(e){alert("son called");e.stopPropagation();},true);
x=document.getElementsByTagName('body')[0];
$("#jmyid").click(function(event){
alert("jquery father called");
event.stopPropagation();
});
$(".j2").click(function(event){
alert("jquery son called");
//event.stopPropagation();
return false;
}); spa

 
 


document.write("Body CSS class: " + x.className);
document.write("<br />");
document.write("An alternate way: ");
document.write(document.getElementById('myid').className);code

</script>

</body>
</html>
相關文章
相關標籤/搜索