<!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事件,以前总是觉得自己不会犯这样的错,直到出错后才会真正记在头脑中。

 

相关文章:

  • 2022-12-23
  • 2021-11-03
  • 2021-07-13
  • 2022-02-03
  • 2021-09-21
  • 2021-12-02
  • 2022-12-23
猜你喜欢
  • 2021-11-13
  • 2022-02-16
  • 2021-04-17
  • 2021-10-18
  • 2022-12-23
  • 2021-07-17
相关资源
相似解决方案