jJavascript window.onload事件的正确用法 [英] jJavascript window.onload event correct usage
问题描述
我有这个循环代码来减少Javascript中的DOM调用,然后重新使用它们。
I have this loop code to reduce the DOM calls in my Javascript, and reuse them.
aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
我被证明,如果在DOM完成之前运行了代码,那么该数组为null。在最后一个html代码之后移动脚本将起作用。
I have been shown that if the code is ran before the DOM is complete, then the array is null. Moving the script after the last html code will work.
所以现在我想将此代码放入 window.onload
事件,因此不必将脚本代码移动到页面底部。但这显然不起作用,因为看起来数组循环是在DOM完成之前执行的。
So now I want to put this code inside the window.onload
event so to not have to move the script code to the bottom of the page. But it apparently does not work because it appears that the array loop is executed before the DOM is completed.
window.onload=function(){
var aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
}
此外,我尝试删除了 var
Also, I have tried to remove the "var" to remove scope without making a difference.
推荐答案
您也可以在不使用框架的情况下尝试这种方法:
You could also try this approach without using a framework:
window.onload = (function(){
return function(){
var aarr = [];
for (var z=1; z<=10; z++) {
aarr.push(document.getElementById("a"+z));
alert(aarr[z-1].id);
}
};
})();
这篇关于jJavascript window.onload事件的正确用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!