一、preventDefault 其阻止默认行为的发生而发生其他的事件,例如:阻止<a> onclick而触发的超链接 <a href="http://www.baidu.com" id="stopL
一、preventDefault
其阻止默认行为的发生而发生其他的事件,例如:阻止<a> onclick而触发的超链接
<a href="http://www.baidu.com" id="stopLink">百度</a><script type="text/javascript"> var test=document.getElementById("stopLink");test.onclick= function(e){ alert(this.href); stopDefault(e);}function stopDefault( e ) { if ( e && e.preventDefault )e.preventDefault(); else window.event.returnValue = false; return false; } </script> -----------------------结果:将不会自动跳转到百度首页,默认跳转事件被阻止执行
二、stopPropagation
子元素触发事件阻止事件冒泡引发父元素事件触发
<div id="parent" style="width:250px;background-color:yellow" onclick="alert(this.id)"> <div id="son" style="width:200px;background-color:green" onclick="stopUp(this,event)"> son </div></div><script type="text/javascript"> function stopUp(obj,evt){ alert(obj.id); var e=evt?evt:window.event; if(window.event){ e.cancelBubble=true; }else{ e.stopPropagation(); } }</script>---------------------------结果:点击son时parent click事件不会被触发,son阻止了冒泡传递