getElementById 和 null - 为什么? [英] getElementById and null - why?

查看:34
本文介绍了getElementById 和 null - 为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码不起作用?我正在使用 FF.

Why doesn't this code work? I'am using FF.

<head>
<script type="text/javascript">

document.getElementById("someID").onclick = function(){
    alert("Yahooo");
}
</script> 
</head>

<body> 
<a href="#" id="someID">someID</a>
</body>

</html>

我收到 javascript 错误 getElementById 等于 null.

I'm getting javascript error getElementById equals to null.

推荐答案

执行脚本时未加载所需的 DOM.将其向下移动(在 href 下方)或如下定义:

The needed DOM is not loaded when the script is executed. Either move it down (below the href) or define it like this:

window.onload = function () {
    document.getElementById("someID").onclick = function(){
        alert("Yahooo");
    }
}

window.onload 将在页面完全加载时调用.

window.onload will be called when the page is completely loaded.

这篇关于getElementById 和 null - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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