预先感谢您的帮助。这是我的第一个带有对象的小项目,这很困难。
我用对象创建了一个板,但我想为我创建的每个 divElt 增加“ID”。 你能帮我吗?
function Plateau(width,height,id){
this.width = width +'px';
this.height = height+'px';
this.id=0;
this.creation = function(){
for (var i = 0; i < 40; i++) {
var divElts = document.createElement('div');
divElts.classList.add('case');
divElts.style.width = this.width;
divElts.style.height = this.height;
divElts.setAttribute = ('id', this.id++);
document.getElementById('contenu').appendChild(divElts);
}
};
}
var board = new Plateau(40,40);
board.creation();
#contenu{
width :440px;
height:440px;
}
.case{
border-radius:20px;
border:solid black 1px;
display:inline-block;
width:200px;
height:200px;
background-color:yellow;
}
<div id="contenu"></div>
谢谢
最佳答案
我的线路有误
divElts.setAttribute = ('id', this.id++);
用
更改它divElts.setAttribute('id', this.id++);
这是优化版本
function Plateau(width,height,id){
this.width = width +'px';
this.height = height+'px';
this.container = document.getElementById(id);
this.id=0;
this.creation = function(){
var fragment = document.createDocumentFragment();
for (var i = 0; i < 40; i++) {
var divElts = document.createElement('div');
divElts.classList.add('case');
divElts.style.width = this.width;
divElts.style.height = this.height;
divElts.setAttribute('id', this.id++);
fragment.appendChild(divElts);
}
this.container.appendChild(fragment);
};
}
var board = new Plateau(40, 40, 'contenu');
board.creation();
关于javascript - 如何用js递增 "id"对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47962992/