getElementById and null - why? [duplicate]

2020-02-07 00:59发布

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>

I'm getting javascript error getElementById equals to null.

2条回答
来,给爷笑一个
2楼-- · 2020-02-07 01:26

Because the element doesn't yet exist when the script runs - the document hasn't been rendered yet. Either run the script in a script block after the related HTML, or use a "document on ready" event handler - preferably from something like jQuery's .ready() event, or the native window.onload.

查看更多
Melony?
3楼-- · 2020-02-07 01:31

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 will be called when the page is completely loaded.

查看更多
登录 后发表回答