document.getElementById()不起作用? [英] document.getElementById() doesn't work?

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

问题描述

没什么可说的

<html>
    <body>
        <script>
            var x = document.getElementById('btn1');
            alert(x);
        </script>
            <input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
    </body>
</html>

警报消息为 null ,而不是包含对象详细信息或类似内容的消息.

The alert message is null instead of a message contain details of the object or something like that.

出什么问题了?

推荐答案

在实际元素之后放置脚本,否则当您的JavaScript代码运行时,DOM中还没有这样的元素.

Put your script AFTER the actual element, otherwise by the time your javascript code runs, there's not yet such element in the DOM.

<html>
    <body>
        <input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
        <script>
            var x = document.getElementById('btn1');
            alert(x);
        </script>
    </body>
</html>

或者将脚本置于DOM ready事件中,以确保浏览器在尝试对其进行操作之前已完全加载了DOM:

Alternatively put your script in a DOM ready event to ensure that the DOM is fully loaded by the browser before attempting to manipulate it:

<html>
    <body>
        <script>
            window.onload = function() {
                var x = document.getElementById('btn1');
                alert(x);
            };
        </script>
        <input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
    </body>
</html>

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

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