html中载入自执行getElementById("xx")得到null
2013-08-21 14:19
483 查看
<!DOCTYPE HTML> <html> <head> <title>Scope Chain & Closure Example </title> <script type="text/javascript"> ( function initAnchors(){ var anchor = document.getElementById('anchor1'); alert(anchor); //想了好久才知道为什么总是null })(); //自执行 </script> </head> <body> <h1>Scope Chain & Closure Example</h1> <ul> <li><a href="#" id="anchor1">Anchor 1</a></li> <li><a href="#" id="anchor2">Anchor 2</a></li> <li><a href="#" id="anchor3">Anchor 3</a></li> </ul> </body> </html>
2.应该改为:
<script type="text/javascript"> function initAnchors(){ var anchor = document.getElementById('anchor1'); alert(anchor); }; </script> </head> <body onload="initAnchors()"> //使用onload事件,以前总是觉得自己不会犯这样的错,直到出错后才会真正记在头脑中。
相关文章推荐
- .net 使用模板页,JS使用document.getElementById("")得到null的解决办法
- 在document.getElementById("oDiv").innerHTML="JS执行问题";
- 关于javascript的getelementbyid得到的为什么为null
- document.getElementById得到null
- document.getElementById("xx").style.xxx中的所有属性
- javascript在html中的加载顺序------为什么window.alert(document.getElementById("time").innerTex)无法弹出对话框
- 【转】document.getElementById("xx").style.xxx中的全部属性
- document.getElementById("DIV名").innerHTML = "你要更新的内容"
- document.getElementById("xx").style.xxx中的所有属性
- $("#id").html(代码内容) VS document.getElementById("id").innerHTML="代码内容";
- jquery中的$("#id")与document.getElementById("id")的区别 及html()方法
- document.getElementById("xx").style.xxx中的所有属性是什么
- document.getElementById("id").innerHTML=""与document.getElementById("id").style.display="none"
- document.getElementById("MyFile")和insertAdjacentHTML("beforeEnd", str)的含义和用法
- document.getElementById("xxForm").submit();不起作用,无效方法??
- document.getElementById("xx").style.xxx中的所有属性
- 关于区别docuemnt.write()和document.getELementById().innerHTML=""
- document.getElementById("xx").style.xxx中的所有属性
- document.getElementById("xx").style.xxx中的所有属性