我有以下代码
<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 之前调用脚本。
将您的脚本包装在一个将调用 onload
的函数中,例如:
window.onload = function() {
var q = new foo();
q.run('yellow');
};
关于javascript - 在 <head> 中执行 JavaScript,getElementById 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5704924/