通过迭代,使用数组

时间:2018-08-11 20:01:28

标签: javascript arrays

我被卡住了。我需要创建4个具有相同类和不同ID的新元素。关键是我不想重复代码...但是我的循环不起作用。

我已经尝试克服大约2个小时的挑战(也在Google中做了大量研究),试图找出使用console.log并在迭代中打印元素的过程。然后,我需要打印console.dir以查看已创建的[object HTMLDivElement]的属性。

代码如下:

columnsArray = ["first", "second", "third", "fourth"]
for (var i = 0; i < columnsArray.length; i++ ) {
    let name = columnsArray[i]
    name = document.createElement("div");
    name.className = "container"
    name.setAttribute("id", name.name)
    document.querySelector("#board" + boardId).appendChild(name);
}

我想知道是否有任何相对简单的方法(值得尝试)实现我的目标?除此之外:

let first = document.createElement("div");
let second = document.createElement("div");
let third = document.createElement("div");
let fourth = document.createElement("div");

first.className = "container"
second.className = "container"
third.className = "container"
fourth.className = "container"

first.setAttribute = "first"
second.setAttribute = "second"
third.setAttribute = "third"
fourth.setAttribute = "fourth"


document.querySelector("#board" + boardId).appendChild(first);
document.querySelector("#board" + boardId).appendChild(second);
document.querySelector("#board" + boardId).appendChild(third);
document.querySelector("#board" + boardId).appendChild(fourth);

预先感谢您的帮助;)

4 个答案:

答案 0 :(得分:1)

您正在通过将循环创建为元素来覆盖columnsArray中的ID值。

在新变量中创建元素:

columnsArray = ["first", "second", "third", "fourth"]

for (var i = 0; i < columnsArray.length; i++ ) {
    // get the ID value from the array
    let name = columnsArray[i];
    // create a new element
    let element = document.createElement("div");
    // set its name
    element.className = "container"
    // set the ID value to columnsArray[i] (name)
    element.setAttribute("id", name)
    // append to board
    document.querySelector("#board" + boardId).appendChild(element);
}

答案 1 :(得分:0)

您的循环效果很好,您只是无法以自己的方式访问名称。

您必须这样设置ID:

name.setAttribute("id", columnsArray[i])

name.name不存在。

columnsArray = ["first", "second", "third", "fourth"];
boardId = 1;
for (var i = 0; i < columnsArray.length; i++ ) {
    let name = document.createElement("div");
    name.className = "container"
    
    name.setAttribute("id", columnsArray[i]) // set name.id to columnsArray[i]
    
    name.innerHTML = "DIV id="+columnsArray[i]
    document.querySelector("#board" + boardId).appendChild(name);
    console.log(name, name.id)
}
<div id="board1"></div>

答案 2 :(得分:0)

使用name.setAttribute("id", columnsArray[i])代替name.setAttribute("id", name.name)

之后使用

name.innerHTML = columnsArray[i]; //Replace it for some info or element
document.querySelector("#board" + boardId).appendChild(name);

答案 3 :(得分:0)

使用此:

columnsArray = ["first", "second", "third", "fourth"]

for (i in columnsArray) {
  let name = columnsArray[i]
  name = document.createElement("div");
  name.className = "container"
  name.setAttribute("id",columnsArray[i])
  document.getElementById('boardId').appendChild(name);
}