在< head>中执行JavaScript,getElementById返回null [英] Executing JavaScript in the <head>, getElementById returns null
本文介绍了在< head>中执行JavaScript,getElementById返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码
<html>
<head>
<script language="JavaScript">
function foo(q) {
this.run=function(color){
var x=document.getElementById("ff");
alert(x); // <----x=null
};
}
var q=new foo();
q.run("yellow");
</script>
</head>
<body>
<div id="ff"></div>
</body>
</html>
没有人知道为什么 x = null
推荐答案
它为 null
,因为您是在加载DOM之前调用脚本的.
It's null
because you're calling the script before the DOM has been loaded.
将脚本包装到一个将在 onload
中调用的函数中,例如:
Wrap your script in a function which will be invoked onload
, e.g.:
window.onload = function() {
var q = new foo();
q.run('yellow');
};
这篇关于在< head>中执行JavaScript,getElementById返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文