JavaScript getElementByID()不起作用 [英] JavaScript getElementByID() not working

查看:169
本文介绍了JavaScript getElementByID()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 refButton 在以下JavaScript代码中获取 null

Why does refButton get null in the following JavaScript code?

<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>


推荐答案

在您调用函数时,其余的该页面的页面尚未呈现,因此该元素在该点不存在。尝试在 window.onload 上调用你的函数。这样的事情:

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<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>

这篇关于JavaScript getElementByID()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆