什么是JS事件冒泡?
在一个对象上触发某类事件(比如单击onclick事件),如果此对象定义了此事件的处理程序,那么此事件就会调用这个处理程序,如果没有定义此事件处理程序或者事件返回true,那么这个事件会向这个对象的父级对象传播,从里到外,直至它被处理(父级对象所有同类事件都将被激活),或者它到达了对象层次的最顶层,即document对象(有些浏览器是window)。
jscript阻止事件冒泡及阻止默认事件的方法
<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的做法
<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>
|
|