[英]Storing DOM reference elements in a Javascript array
Dear experts, I was trying to dynamically generate DOM elements using JS. 亲爱的专家,我试图用JS动态生成DOM元素。
I read from Douglas Crockford's book that DOM is very very poorly structured. 我从Douglas Crockford的书中读到,DOM的结构非常糟糕。
Anyways, I would like to create a number of DIVISION elements and store the reference into an array so it could be accessed later. 无论如何,我想创建一些DIVISION元素并将引用存储到一个数组中,以便以后可以访问它。
Here's the code 这是代码
for(i=0; i<3; i++) {
var div = document.body.appendChild(document.createElement("div"));
var arr = new Array();
arr.push(div);
}
Somehow this would not work..... There is only 1 div element created. 不知何故,这将无法工作.....只创建了1个div元素。 When I use the
arr.length
to test the code there is only 1 element in the array. 当我使用
arr.length
来测试代码时,数组中只有1个元素。
Is there another way to accomplish this? 还有另一种方法来实现这一目标吗?
Thanks in advance 提前致谢
You are recreating the array with each iteration (and thus blanking it). 您将在每次迭代时重新创建数组(从而消隐它)。
I think you want something like this. 我想你想要这样的东西。
var arr = []; // more succinct version of new Array();
for (var i = 0; i < 3; i++) {
var div = document.body.appendChild(document.createElement('div'));
arr.push(div);
};
You're making a separate array each time the loop runs. 每次循环运行时,您都会创建一个单独的数组。
Therefore, each array instance 因此,每个数组实例
You need to move the arr
variable outside the loop. 您需要在循环外移动
arr
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.