javascript window.onload事件正确用法 [英] javascript 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 $ c $中c>事件,所以不必将脚本代码移动到页面底部。但它显然不起作用,因为看起来数组循环在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);
}
};
})();
这篇关于javascript window.onload事件正确用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!