我今晚在使用document.getElementById时遇到了奇怪的行为。在Firefox 3和Safari中复制。document.getElementById在函数中失败
基本上,它在Example1中找到ID为“divid”的div。但是,在Example2中它总是返回null。这里发生了什么?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript">
addelement = function(){
alert(document.getElementById('divid'));
}
//Example1
window.onload = function(){ alert(document.getElementById('divid')); }
//Example2
window.onload = addelement();
</script>
<body>
<div id="divid" class="divclass">
<p>Test</p>
</div>
<body>
</html>