[英]Variable is Undefined
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<script type="text/javascript" src="lb-core.js"></script>
<script type="application/javascript">
var lbp = {
defaults: {
color: "blue"
},
init: function(config) {
if(config) {
for(prop in config){
setBgcolor.defaults[prop] = config[prop];
}
}
var bod = document.body;
bod.style.backgroundColor = setBgcolor.defaults.color;
}
}
window.onload = lbp.init();
</script>
</HEAD>
<body>
<div id="container">test</div>
</body>
</HTML>
Why does bod come back as undefined when the above is called at window.onload? 当在window.onload调用以上命令时,为什么bod返回undefined?
Change it to 更改为
window.onload = lbp.init;
When you write window.onload = lbp.init()
, you are calling the init
function, and assigning whatever it returns to window.onload
. 当您编写window.onload = lbp.init()
,您正在调用 init
函数,并将返回的任何内容分配给window.onload
。
Therefore, the function is being called immediately (before the window is loaded), and you're assigning undefined
to window.onload
. 因此,该函数被立即调用(在加载窗口之前),并且您将undefined
分配给window.onload
。 (Because init
doesn't return anything) (因为init
不返回任何内容)
You need to assign the init
function itself to onload
without calling it. 您需要将init
函数本身分配给onload
而不调用它。
Your code needs a few teaks, here's an overall fix: 您的代码需要一些柚木,这是一个整体解决方案:
var lbp = {
defaults: {
color: "blue"
},
init: function(config) {
if(config) {
for(prop in config){
lbp.defaults[prop] = config[prop];
}
}
var bod = document.body;
bod.style.backgroundColor = lbp.defaults.color;
}
}
window.onload = lbp.init;
Previous it was calling init
instantly because window.onload = lbp.init()
was assigning the result of lbp.init
to the onload function, not assigning the actual function, this is fixed above. 以前它被调用init
即刻因为window.onload = lbp.init()
被分配的结果 lbp.init
到的onload函数,而不是分配的实际功能,这是上述固定的。
Also, not sure where setBgcolor
comes from in your code, I believe you meant lbp
here, it works in the same code above, give it a test. 另外,不确定setBgcolor
在您的代码中来自哪里,我相信您的意思是lbp
,它在上面的相同代码中起作用,请对其进行测试。
Try this: 尝试这个:
var bod = document.body;
I don't know why bod
comes back as undefined in your code.. it works for me in Chrome. 我不知道为什么bod
会以您的代码中未定义的形式返回。.它在Chrome中对我有效。 What browser are you running? 您正在运行什么浏览器?
Also, are you sure it's bod
that's undefined? 另外,您确定它是未定义的bod
吗? Not setBgcolor
or something else? 不是setBgcolor
还是其他东西?
EDIT : 编辑 :
Change this line of code: 更改以下代码行:
window.onload = lbp.init();
To this: 对此:
window.onload = lbp.init;
You're currently assigning the result of lpd.init() to onload
.. you need to just assign the reference. 您当前正在将lpd.init()的结果分配给onload
..您只需要分配引用即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.