使用.innerHTML创建div元素会产生意外结果

时间:2015-12-24 22:35:12

标签: javascript jquery html

我试图创建一个Div数组,但下面的代码运行不正确。

运行错误的JS代码(下面的实际JS): http://codepen.io/anon/pen/admWpm

var n=4;        //no. of Triangles
    var j=1; // j is just used to number the triangles
     for(var i=1;i<n;i++)
        {
        document.body.innerHTML+='<div class="row row'+i+'">';  //Open row div

        //Create squares
            for(var k=0;k<n;k++){
                if (k % 2 === 0) {  //Even squares
                    document.body.innerHTML+='<div class="square square1 '+(j++)+'"></div>';
                }
                else{               //Odd squares
                    document.body.innerHTML+='<div class="square square2 '+(j++)+'"></div>';
                }
            }
    document.body.innerHTML+='</div>'; //close row div
    }

简化输出:

<div class="row row1"></div>
<div class="square square1"></div>
<div class="square square2"></div>
<div class="square square3"></div>
<div class="square square4"></div>
<div class="row row2"></div>
<div class="square square5"></div>
<div class="square square6"></div>
<div class="square square7"></div>
<div class="square square"></div>

我想要的输出:

<div class="row row1"></div>
<div class="square square1"></div>
<div class="square square2"></div>
<div class="square square3"></div>
<div class="square square4"></div>
</div>
<div class="row row2">
<div class="square square5"></div>
<div class="square square6"></div>
<div class="square square7"></div>
<div class="square square"></div>
</div>

我认为我错误地使用了innerHTML

1 个答案:

答案 0 :(得分:1)

这是一个使用DOM方法创建和追加元素的快速示例。

&#13;
&#13;
var n = 4; //no. of Triangles
var j = 1; // j is just used to number the triangles

for (var i = 1; i < n; i++) {
  var d = document.body.appendChild(document.createElement("div"));
  d.className = "row row" + i;

  //Create squares
  for (var k = 0; k < n; k++) {
    var s = d.appendChild(document.createElement("div"));
    s.textContent = "i:" + i + ", j:" + j;
    s.className = "square square" + ((k % 2) + 1) + " " + j++;
  }
}
&#13;
.square {
  width: 70px; 
  height: 30px;
  margin: 4px;
  background: orange;
  color: white;
  }
.square2 {
  background: red;
  }
&#13;
&#13;
&#13;

代码中的square类似乎与您想要的输出相匹配,因此您可能需要稍微调整一下。

我添加了一些文本内容和CSS,以便更容易查看输出。