使用两个id变量在循环中更改id div

时间:2015-10-15 19:57:24

标签: javascript html

下午好。

我试图在一个div中创建一个循环,其中两个div id(" uno"," otro")将被替换为相同的div不时

直到现在我



setInterval(function() {
  loop = 2;
  total = 0;
  for (i = 0; i < loop; i++) {
    total += 1;
    if (total == loop)
      var casa = "uno";


    else
      var casa = "otro";
  }
  var div = document.createElement("div");
  div.id = casa;
  document.body.appendChild(div);
  console.log(div)
}, 5000);
&#13;
&#13;
&#13;

但只打印一个div,请一点帮助

1 个答案:

答案 0 :(得分:2)

将追加/创建逻辑移动到循环中:

setInterval(function() {
    loop = 2;
    total = 0;
    for (i = 0; i < loop; i++) {
        var casa = "";
        total += 1;
        if (total == loop) casa = "uno";
        else casa = "otro";

        var div = document.createElement("div");
        div.id = casa;
        document.body.appendChild(div);
        console.log(div)
    }

}, 5000);

根据您的意见,您的问题真的不清楚,例如,DOM在初始时是否存在?我将向您展示一个代码,该代码将检查div是否已经附加,否则它只会更改id:

var appended = false, currentId = "";
setInterval(function() {
    loop = 2;
    total = 0;
    for (i = 0; i < loop; i++) {
        var casa = "";
        total += 1;
        if (total == loop) casa = "uno";
        else casa = "otro";
    }

    var div = !appended ? document.createElement("div") : document.getElementById(currentId);
    div.id = casa;
    if (!appended) document.body.appendChild(div);
    console.log(div);
    appended = true;
    currentId = casa;
}, 5000);

但是有了这个,你总会获得相同的id,你应该检查以前的id而不是循环:

var appended = false, currentId = "";
setInterval(function() {
    var casa = currentId === "uno" ? "otro" : "uno";

    var div = !appended ? document.createElement("div") : document.getElementById(currentId);
    div.id = casa;
    if (!appended) document.body.appendChild(div);
    console.log(div);
    appended = true;
    currentId = casa;
}, 5000);