循环创建2d数组

时间:2018-06-16 13:40:03

标签: javascript arrays html5

我想从div中创建一个带有类的div中的二维数组。据我所知,这段代码给了我一个数组,但是我无法访问数组中的对象,这是错误的吗?



var frames;
var myElements = [];
var animatedClasses = ["text", "splash"];

for (var i = 0; i < frames.length; i++) {
    for (var j = 0; j < animatedClasses.length; j++) {
        myElements[[i], [i, [j]]] = frames[i].getElementsByClassName(animatedClasses[j]);
    }
}
myElements[0,0].style.opacity = "0.5"; // DOESN'T WORK

}
&#13;
<div class="frame">
    <div class="splash"></div>
    <div class="text"></div>
</div>

<div class="frame">
    <div class="splash"></div>
    <div class="text"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码

var frames = document.getElementsByClassName('frame');
var myElements = [];
var animatedClasses = ["text", "splash"];

for (var i = 0; i < frames.length; i++) {
    if(!myElements[i]) myElements[i] = Array(animatedClasses.length);
    for (var j = 0; j < animatedClasses.length; j++) {
        myElements[i][j] = frames[i].getElementsByClassName(animatedClasses[j])[0];
      }
 }
 console.log(myElements);
 myElements[0][1].style.opacity = "0.5"; // DOESN'T WORK
  myElements[0][1].style.color = "red";
<div class="frame">
    <div class="splash"> Hello</div>
    <div class="text"></div>
</div>

<div class="frame">
    <div class="splash"></div>
    <div class="text"></div>
</div>