"的getElementsByTagName(...)[0]"未定义 [英] "getElementsByTagName(...)[0]" is undefined?

查看:195
本文介绍了"的getElementsByTagName(...)[0]"未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <!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>按此处< / h1>
< img src =1.jpg>< / img>
< / body>
< / html>

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

  hbutton未定义
---
hbutton.onclick = function(){

当我在页面加载之后运行JS时,它的工作非常好!为什么是这样?

解决方案

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


之前

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.

    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?

解决方案

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

这篇关于&QUOT;的getElementsByTagName(...)[0]&QUOT;未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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