一尘不染

JavaScript getElementByID()无法正常工作

javascript

为什么会refButton获得null以下JavaScript代码?

<html>
<head>
    <title></title>
    <script type="text/javascript">
        var refButton = document.getElementById("btnButton");

        refButton.onclick = function() {
            alert('I am clicked!');
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

阅读 321

收藏
2020-05-01

共1个答案

一尘不染

此时,您正在调用函数,页面的其余部分尚未呈现,因此该元素当时不存在。尝试调用您的函数window.onload。像这样:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>
2020-05-01