JavaScript脚本中调用了位于脚本位置之后的标签,可能会导致getElementById的返回值为空
原因:JavaScript调用了尚未加载的标签
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var t=document.getElementById("mes");
//运行时发现t==null
</script>
</head>
<body >
the message is:<input type="text" id="mes"/>
</body>
解决办法:
把放在body之后
或者设置body的onload事件
<head>
<script type="text/javascript">
function myfunction(){
var t=document.getElementById("mes");
}
</script>
</head>
<body onload="myfunction()">
the message is:<input type="text" id="mes"/>
</body>
<script type="text/javascript">
window.onload = function(){
var t=document.getElementById("mes");
}
</script>
</head>
<body>
the message is:<input type="text" id="mes"/>
</body>
欢迎交流讨论