创建一个10x10的字段

时间:2018-10-03 20:44:35

标签: javascript html

我有这段代码,看起来正确,但是为什么新的div不会出现在父div中。有人可以向我解释原因吗?

var myGame = {
  fieldSize: 10,
  drawField: function() {
    setInterval(function () { 

      var parent = document.getElementById('parent')
      parent.innerHTML = '';
      for (var i=0; i<this.fieldSize; i++) {
        var row = document.createElement('div');
        for (var j=0; j<this.fieldSize; j++) {
          var field = document.createElement('div');
          field.className = 'field';      
          row.appendChild(field);
        }
        parent.appendChild(row);      
      }
    }, 3000)
  }
}
myGame.drawField()
<div id="parent"></div>

1 个答案:

答案 0 :(得分:1)

您的setInterval创建了另一个上下文,因此this.fieldSizeundefined

var myGame = {
  fieldSize: 10,
  drawField: function() {
    setInterval(() => { 

      var parent = document.getElementById('parent')
      parent.innerHTML = '';
      for (var i=0; i<this.fieldSize; i++) {
        var row = document.createElement('div');
        for (var j=0; j<this.fieldSize; j++) {
          var field = document.createElement('div');
          field.className = 'field';			
          row.appendChild(field);
        }
        parent.appendChild(row);			
      }
    }, 3000)
  }
}
myGame.drawField()
<div id="parent"></div>