我有这段代码,看起来正确,但是为什么新的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>
答案 0 :(得分:1)
您的setInterval创建了另一个上下文,因此this.fieldSize
是undefined
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>