JavaScript getElementByID()无法正常工作

为什么会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>


繁星点点滴滴
浏览 453回答 3
3回答

慕婉清6462132

此时,您正在调用函数,页面的其余部分尚未呈现,因此该元素当时不存在。尝试调用您的函数window.onload。像这样:<html><head>&nbsp; &nbsp; <title></title>&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; window.onload = function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var refButton = document.getElementById("btnButton");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; refButton.onclick = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('I am clicked!');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; </script></head><body>&nbsp; &nbsp; <form id="form1">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input id="btnButton" type="button" value="Click me"/>&nbsp; &nbsp; </div>&nbsp; &nbsp; </form></body></html>

Cats萌萌

您需要将JavaScript 放在body标签的末尾。它找不到它,因为它不在DOM中!您也可以将其包装在onload事件处理程序中,如下所示:window.onload = function() {var refButton = document.getElementById( 'btnButton' );refButton.onclick = function() {&nbsp; &nbsp;alert( 'I am clicked!' );}}

慕容708150

因为执行脚本时浏览器尚未解析<body>,所以它不知道存在具有指定ID的元素。尝试以下方法:<html><head>&nbsp; &nbsp; <title></title>&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; &nbsp; &nbsp; window.onload = (function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var refButton = document.getElementById("btnButton");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; refButton.onclick = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('Dhoor shala!');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; </script>&nbsp; &nbsp; </head><body>&nbsp; &nbsp; <form id="form1">&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input id="btnButton" type="button" value="Click me"/>&nbsp; &nbsp; </div></form></body></html>请注意,您也可以使用addEventListener而不是window.onload = ...使该函数仅在整个文档被解析后才执行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript