本文介绍了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 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 01:52