HTML代码:
<div id="swap">
<div id="box">
<a href="http://www.baidu.com" id="btn">点我</a>
</div>
</div>
js代码:
var swap=document.getElementById("swap");
var box=document.getElementById("box");
var btn=document.getElementById("btn");
swap.οnclick=function(){
alert("我是swap");
};
box.οnclick=function(){
alert("我是box");
}
1.阻止冒泡事件方法 event.stopPropagation();
btn.οnclick=function(e){
var event=window.event||e;
alert("我是btn");
window.event?event.cancelBubble=true:event.stopPropagation();
}
这样只阻止了冒泡事件并未阻止a标签跳转到百度页面的默认事件;弹出“我是btn”点击确定后跳转到百度页面
2. 阻止默认事件方法 event.preventDefault();
btn.οnclick=function(e){
var event=window.event||e;
alert("我是btn");
event.preventDefault();
}
阻止了a标签跳转百度的默认事件,依次弹出“我是btn”“我是box”“我是swap”而不会调到百度页面
3.阻止冒泡和默认事件 event.stopPropagation(); return false;
btn.οnclick=function(e){
var event=window.event||e;
alert("我是btn");
window.event?event.cancelBubble=true:event.stopPropagation();
return false;
}
既阻止了冒泡事件也阻止了默认事件,只弹出“我是btn”;
个人总结,希望能帮到你