大神幫忙看看,為什么點擊頁面任何地方都沒有彈框出現(xiàn)???錯誤提示為Cannot set property 'onclick' of null 。這是什么意思??代碼該如何改??
<!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>
2016-08-16
<!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>
代碼是按順序執(zhí)行,你獲取id =a的元素時,dom未加載完成,所以是null,腳本放在最下邊也可以