jJavascript window.onload事件正确用法
我有这个循环代码来减少 Javascript 中的 DOM 调用,并重用它们。
aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
我已经证明,如果代码在 DOM 完成之前运行,则数组为空。将脚本移到最后一个 html 代码之后即可。
所以现在我想将此代码放入 window.onload
事件中,这样就不必将脚本代码移动到页面底部。但它显然不起作用,因为看起来数组循环是在 DOM 完成之前执行的。
window.onload=function(){
var aarr = [];
for (var z=1; z<=10; z++) {
c = z-1;
aarr[c] = document.getElementById("a"+z);
}
}
另外,我尝试删除“var”以删除范围而不产生任何影响。
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);
}
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.
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);
}
}
Also, I have tried to remove the "var" to remove scope without making a difference.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您也可以在不使用框架的情况下尝试这种方法:
JSFiddle
You could also try this approach without using a framework:
JSFiddle
如果您可以使用 jquery,那么您可以使用文档就绪侦听器:
http://www.jquery.com
作为根据上面的评论,您是否尝试过:
If you can use jquery, then you can use the document ready listener:
http://www.jquery.com
as per the comment above, have you tried:
MDN - window.onload
我猜您尝试在 onload 之外调用代码。 查看这个小提琴
MDN - window.onload
I guess you try calling code outside of onload. See this fiddle
最好使用不预扫描 dom 的函数来创建缓存,当您使用带有缓存构造的简单函数时,不需要预扫描。使用 jQuery,您可以创建这样的函数(下面是本机 javascript 方法):
或者没有框架(本机 javascript):
所以您可以这样做:
就可以了。
欧文·汉杰斯·格雷茨
Better to use a function without pre-scanning the dom to create a cache, Pre-scanning is not needed when you use a simple function with a cache construction. With jQuery you can can create a function like this (native javascript method below this):
Or without a framework (native javascript):
So you can do:
That does the trick.
Greetz, Erwin Haantjes