Javascript “getElementsByTagName(...)[0]”未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10807156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:01:23  来源:igfitidea点击:

"getElementsByTagName(...)[0]" is undefined?

javascripthtmlevents

提问by Bobby Tables

I have the following code, which basically toggles through a bunch of images.

我有以下代码,它基本上可以切换一堆图像。

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            var num = 1;
            img = document.getElementsByTagName("img")[0];
            hbutton = document.getElementsByTagName("h1")[0];
            hbutton.onclick = function() {
                num += 1;
                img.src = num + ".jpg";
            }
        </script>
    </head>
    <body>
        <h1>Press Here!</h1>
        <img src = "1.jpg"></img>
    </body>
</html>

For some reason, when I run it, nothing happens, because of the following error as displayed by my Firebug console.

出于某种原因,当我运行它时,没有任何反应,因为我的 Firebug 控制台显示了以下错误。

    hbutton is undefined    
---
    hbutton.onclick = function() {

When I run just the JS after the page has loaded however, it works perfectly fine!!! Why is this?

然而,当我在页面加载后只运行 JS 时,它运行得非常好!!!为什么是这样?

回答by Julian

Your code is executing before the h1 tag is defined. You must run it in an onload handler or put it just before /body

您的代码在定义 h1 标签之前正在执行。您必须在 onload 处理程序中运行它或将它放在 /body 之前

回答by Lukx

JavaScript is interpreted top-to-bottom. So at the place where your <script>executes, no h1tags are known yet.

JavaScript 从上到下解释。所以在你<script>执行的地方,还没有h1标签是已知的。

Try putting the <script>-Tag to the bottom of your page. Otherwise, if you need the script at the beginning of the page, an onLoad-Handler might help:

尝试将<script>-Tag 放在页面底部。否则,如果您需要页面开头的脚本,则 onLoad-Handler 可能会有所帮助:

<script type="text/javascript">
    function onLoadHandler() {
         // your original javascript code here...
    }
</script> 
<body onload="onloadHandler()">
<!-- HTML Code here-->

回答by Joel

When you put it in the header, your h1 is not loaded yet. hbutton becomes undefined, not an object. Then when you try to set .onclick, it breaks because you cant set properties of something undefined. When you put the code in the body, your h1 is already loaded, so the code works as you expected it to.

当你把它放在标题中时,你的 h1 还没有加载。hbutton 变为未定义,而不是对象。然后,当您尝试设置 .onclick 时,它会中断,因为您无法设置未定义内容的属性。当您将代码放入正文时,您的 h1 已经加载,因此代码按您的预期工作。

You can fix this by leaving your code at the top, but only calling it after an onload event.

您可以通过将代码保留在顶部来解决此问题,但只能在 onload 事件之后调用它。

回答by Michael Koper

The head gets executed before the dom is loaded. Put it on the button of the page or put an onload function in the body tag.

在加载dom之前执行头部。放在页面的按钮上或者在body标签里放一个onload函数。

It cannot find document.getElementsByTagName("img") when the Document isnt ready yet, because it is simply not there yet.

当 Document 尚未准备好时,它无法找到 document.getElementsByTagName("img") ,因为它根本就不存在。

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
          function onDocumentReady(){
            var num = 1;
            img = document.getElementsByTagName("img")[0];
            hbutton = document.getElementsByTagName("h1")[0];
            hbutton.onclick = function() {
                num += 1;
                img.src = num + ".jpg";
            }
          }  
        </script>
    </head>
    <body onload="onDocumentReady()">
        <h1>Press Here!</h1>
        <img src = "1.jpg"></img>
    </body>
</html>

or simply do this:

或者干脆这样做:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <h1>Press Here!</h1>
        <img src = "1.jpg"></img>
        <script type="text/javascript">
            var num = 1;
            img = document.getElementsByTagName("img")[0];
            hbutton = document.getElementsByTagName("h1")[0];
            hbutton.onclick = function() {
                num += 1;
                img.src = num + ".jpg";
            }
        </script>
    </body>
</html>

回答by Spudley

The problem is that the script is being executed immediately it is encountered during page load.

问题是在页面加载期间遇到脚本会立即执行。

Since it's at the top of the page, in the header, this means that it is executed before the page has loaded the <h1>element (or any of the rest of the body).

由于它位于页面顶部,在标题中,这意味着它在页面加载<h1>元素(或正文的任何​​其余部分)之前执行。

Therefore, when it asks for getElementsByTagName('h1'), there aren't any matching elements at that moment in time.

因此,当它要求getElementsByTagName('h1')时,此时没有任何匹配的元素。

You need to either: * move the code to the end of the script. * or wrap it in a function, and trigger the function to execute when the page has finished loading -- ie use the onloadmethod.

您需要: * 将代码移动到脚本的末尾。* 或将其包装在一个函数中,并在页面加载完成时触发该函数执行——即使用该onload方法。