document.getElementById(...) is null


<html>
    <head>
        <script type="text/javascript">
            document.getElementById('btn1').onclick=function(){
                alert('helleo');
            };
        </script>
    </head>
    <body>
        <input type="button" name="name" value="button" id="btn1"/>
    </body>
</html>

 

如果js代碼像上面這樣寫就會報錯:document.getElementById(...) is null,原因是按從上到下得執行順序,執行js代碼得時候還沒有注冊id為btn1得button,所以根據id獲得得對象就為空,所以得將上面得js代碼寫到一個window.onload方法里面,意思是頁面加載完畢以后再執行內部得js代碼

<html>
    <head>
        <script type="text/javascript">
        window.onload=function(){
            document.getElementById('btn1').onclick=function(){
                alert('helleo');
            };
        };
        </script>
    </head>
    <body>
        <input type="button" name="name" value="button" id="btn1"/>
    </body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM