getElementById返回空值 [英] `getElementById` returning null

查看:97
本文介绍了getElementById返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

document.getElementById返回null的情况.我已经阅读了SO中的其他四个问题,并阅读了有关MDN的参考资料,但是我不知道这是怎么回事.请帮我.代码如下:

A case of document.getElementById returning null. I've read four other questions in SO, and read the reference on MDN, but I have no clue of what's wrong; please help me. Code is as follows:

HTML

<button id="btnButton1">Button1!</button><br>
<button id="btnButton2">Button2!</button><br>
<span id="spanOutPut"></span>

JavaScript

Javascript

getBYid = function(elem) {
    return document.getElementById(elem); }

funButton1 = function() { getBYid('spanOutPut').innerHTML = "Button 1 pressed!!" };
funButton2 = function() { getBYid('spanOutPut').innerHTML = "Did you press the Button 2?!" };

getBYid("btnButton1").addEventListener('click', funButton1, false);
getBYid("btnButton2").addEventListener('click', funButton2, false);

在FireBug上,我得到一个TypeError: getBYid(...) is null.

I get a TypeError: getBYid(...) is null, on FireBug.

当我简单地从JS中删除对addEventListener的调用并设置内联onclick时,它会起作用,如以下代码所示:

It works when I simply remove the calls to addEventListener from the JS and set onclick inline, as in the following code:

<button onclick="funButton1()">Button1"</button>

有什么区别?

推荐答案

您必须在将这些元素加载到DOM之后将其放入

You have to put this after those elements have been loaded into the DOM

这篇关于getElementById返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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