欢迎加入qq群(IT-程序猿-技术交流群):757345416
事件冒泡
触发顺序由内向外可称为事件冒泡。
html部分
<div id="one">
<div id="two"></div>
</div>
<a href="http://www.chao99.top" id="href">初心-杨瑞超个人博客</a>
css部分
<style type="text/css">
#one{
width: 200px;
height: 200px;
background: red;
}
#two{
width: 60px;
height: 60px;
background: #090;
}
</style>
js部分
<script type="text/javascript">
var one=document.getElementById('one');
var two=document.getElementById('two');
var href=document.getElementById('href');
//阻止冒泡start
one.onclick=function(){
alert("one");
}
two.onclick=function(e){
var oEvent = e || event;
oEvent.stopPropagation();
alert("two");
}
//阻止冒泡end
//阻止默认事件start
href.onclick=function(e){
alert("超链接");
var oEvent = e || event;
oEvent.preventDefault();
return false;
}
//阻止默认事件end
</script>
jQuery解决办法
引入jQuery
<script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
jQuery代码部分
<script type="text/javascript">
//阻止冒泡start
$("#one").click(function(){
alert("one");
});
$("#two").click(function(event){
alert("two");
event.stopPropagation();
});
//阻止冒泡end
//阻止默认事件start
$("#href").click(function(event){
event.preventDefault();
});
//阻止默认事件end
//阻止冒泡&默认事件start
$("#two #href").click(function(event){
return false;
});
//阻止冒泡&默认事件end
</script>
图解:
此文章到此结束,希望对你的学习有帮助。