弹出错误:Cannot read property 'nodeName' of null" 为什么呢?

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<style>

</style>

<script>

window.onload = function(){

var fn={

plus1:function(a,b){  //var plus=function(a,b){  不能这样,因为自己已在变量的定义里

return a+b;

},

minus1:function(a,b){

return a-b;

}

}

//alert(fn.plus1);

document.write(fn.plus1(1,2)+'<br />');

document.write(fn.minus1(3,2)+'<br />');

var odiv=document.getElementById("div");

document.write(odiv.nodeName+'<br />'+odiv.nodeType+'<br />'+odiv.nodeValue);

}

</script>

</head>

<body>

<div id="div">12</div>

</body>

</html>

弹出错误:Cannot read property 'nodeName' of null"  为什么呢?

qq_ggJKING_LWJ_0
浏览 5797回答 2
2回答

Caballarii

var odiv=document.getElementById("div");这句被你写在window.onload外面了,就不会在div加载之后执行,取不到所以会是null。建议弄个编辑器把代码格式化一下,要不然很容易看不清大括号括到哪里,比如你这里minus1后面就多了一个大括号,导致后面的代码在window.onload外面了

小董ong123456

刷新一下页面
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript