html中载入自执行getElementById("xx")得到null

<!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事件,以前总是觉得自己不会犯这样的错,直到出错后才会真正记在头脑中。
原文地址:https://www.cnblogs.com/yuyutianxia/p/3272561.html