周耀勇
2016-08-16 01:15
<!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,脚本放在最下边也可以
DOM事件探秘
99545 学习 · 1197 问题
相似问题