Javascript TypeError:表达式的结果不是对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5754224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript TypeError: result of expression is not an object
提问by Abhishek
This should be real simple... But it ain't... >.<
这应该很简单...但它不是...>.<
var x = document.getElementById('x');
function snooze()
{
x.style.height = '10px';
}
Upon execution, the error I get is:
执行后,我得到的错误是:
TypeError: Result of expression 'x' [null] is not an object.
TypeError: Result of expression 'x' [null] is not an object.
Edit: Heads up, it works when I put the var declaration inside the function. I don't understand... :-(
编辑:注意,当我将 var 声明放在函数中时它会起作用。我不明白... :-(
function snooze()
{
var x = document.getElementById('x');
x.style.height = '10px';
}
回答by David Tang
Either:
任何一个:
- There is no element on the page with
id="x"
. - The code is running before the document is loaded.
- 页面上没有带有 的元素
id="x"
。 - 代码在加载文档之前运行。
If an element with id="x"
exists, try:
如果id="x"
存在的元素,请尝试:
window.onload = function () {
// your code in here
};