<!doctype html>
<html>
<head>
<style>
#a{
width:200px;
height:200px;
background-color:red;
}
</style>
<script>
var dk=document.getElementById("a");
dk.onclick=function(e){
e = e || window.e;
if(e.stopPropagation){
e.stopPropagation();
}else{
e.cancelBubble=true;
}
}
document.onclick=function(){
alert('hello');
}
</script>
</head>
<body>
<div id="a">
</div>
</body>
</html>
<!doctype html>
<html>
<head>
<style>
#a {
width: 200px;
height: 200px;
background-color: red;
}
</style>
<script>
window.onload =function () {
// body...
var dk = document.getElementById("a");
dk.onclick = function(e) {
alert("message")
e = e || window.e;
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
document.onclick = function() {
alert('hello');
}
}
</script>
</head>
<body>
<div id="a">
</div>
</body>
</html>
代码是按顺序执行,你获取id =a的元素时,dom未加载完成,所以是null,脚本放在最下边也可以