事件冒泡的机制:是从里向外传播的,如下代码如果没有阻止事件冒泡,则,点击span的时候,先弹出芬芬,再弹出
我是<span id="spanId">芬芬</span>
事件由span传到div,其实前提是两者都绑定了点击事件,才会因为点击了span,传到div。同时绑定其他事件也一样的。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>创维</title>
<script>
window.onload = function(){
var id= document.getElementById("id");
id.οnclick=function(event){
alert(this.innerHTML);
}
var spanid= document.getElementById("spanId");
spanid.οnclick=function(event){
stopPropagation(event);//如果注释掉这条,事件将冒泡
alert(this.innerHTML);
}
function stopPropagation(event){
if(event&&event.stopPropagation){
event.stopPropagation();
}else{
window.event.cancelBubble=true;
}
}
}
</script>
<style>
#id{padding:20px;background-color:red;}
#spanId{background-color:pink;}
</style>
</head>
<body>
<div id="id">我是<span id="spanId">芬芬</span></div>
</body>
</html>
阻止默认行为
实现a的链接不跳转
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>创维</title>
<script>
window.onload = function(){
var preventDefault = function(event){
if(event&&event.preventDefault){
event.preventDefault();
}else{
window.event.returnValue = false;
}
return false;
}
var mya = document.getElementsByTagName("a");
mya[0].onclick = function(){
preventDefault(event);
}
}
</script>
</head>
<body>
<a href="#" target="_brank" id="mya">链接</a>
</body>
</html>