为什么头部选择中的javascript代码不能获得元素? [英] Why can't my javascript code in the head selection get an element?

查看:53
本文介绍了为什么头部选择中的javascript代码不能获得元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在javascript中使用pi计算器很长一段时间了,我终于完成了。问题是我在head节中的脚本:

I have been working on a pi calculator in javascript for a long time now and I have finally finished. The problem is that my script in the head section:

document.getElementById("button").addEventListener('click', (function(){
    alert('Beginning…');
}), false);

我的身体部分有这个:

<input type="button" id="button" value="Calculate!!"/>

但是当我打开网页时,我收到以下错误:null不是对象,评估document.getElementById(button)。addEventListener

But when I open the webpage, I get the following error: "null is not an object, evaluating document.getElementById("button").addEventListener"

有谁知道我的代码无法正常运行的原因?

Does anyone know why my code isn't functioning properly?

谢谢。

推荐答案

将其包裹在上窗口 onload 事件:

window.onload = function()
{
    document.getElementById("button").addEventListener('click', (function(){
        alert('Beginning…');
    }), false);
};

window.addEventListener('load', function()
{
    document.getElementById("button").addEventListener('click', (function(){
        alert('Beginning…');
    }), false);
});

或者,如果您的脚本不必在头部,将它放在ID为按钮的元素之后。

or, if your script doesn't have to be in the head, put it after the element that has the id of button.

DEMO

DEMO

这篇关于为什么头部选择中的javascript代码不能获得元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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