冒泡与默认行为

mac2026-05-10  1

冒泡

w3c的方法是e.stopPropagation(),IE则是使用e.cancelBubble = true
// 阻止冒泡方式一 // return false $('.son').click(()=>{ alert('我是son的事件'); return false; }) // 阻止冒泡方式二 // event.stopPropagation() $('.son').click((event)=>{ alert('我是son的事件'); event.stopPropagation() })

兼容

//兼容一 window.event? window.event.cancelBubble = true : e.stopPropagation(); //兼容二 function stopBubble(e) { //如果提供了事件对象,则这是一个非IE浏览器 if ( e && e.stopPropagation ) //支持stopPropagation()方法 e.stopPropagation(); else //否则,我们需要使用IE的方式来取消事件冒泡 window.event.cancelBubble = true; }

默认行为

w3c的方法是e.preventDefault(),IE则是使用e.returnValue = false;
//阻止默认行为方式一 $('a').click(()=>{ alert('填写注册框') return false; }) //阻止默认行为方式二 $('a').click((event)=>{ alert('填写注册框') event.preventDefault() })

兼容

//阻止浏览器的默认行为 function stopDefault( e ) { //阻止默认浏览器动作(W3C) if ( e && e.preventDefault ) e.preventDefault(); //IE中阻止函数器默认动作的方式 else window.event.returnValue = false; return false; }
最新回复(0)