JavaScript getElementByID() not working [duplicate]

本秂侑毒 提交于 2019-11-26 02:58:43

问题


This question already has an answer here:

  • Why does jQuery or a DOM method such as getElementById not find the element? 8 answers

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>

回答1:


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>



回答2:


You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
   alert( 'I am clicked!' );
}
}



回答3:


Because when the script executes the browser has not yet parsed the <body>, so it does not know that there is an element with the specified id.

Try this instead:

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

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

Note that you may as well use addEventListener instead of window.onload = ... to make that function only execute after the whole document has been parsed.



来源:https://stackoverflow.com/questions/1829925/javascript-getelementbyid-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!