您的位置:首页 > Web前端 > HTML

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事件,以前总是觉得自己不会犯这样的错,直到出错后才会真正记在头脑中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐