【发布时间】:2017-12-24 18:08:40
【问题描述】:
提前感谢您的帮助。这是我第一个有对象的小项目,很难。
我用对象创建了一个板,但我想为我创建的每个 divElts 增加“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>
谢谢
【问题讨论】:
-
从您的代码中不清楚您尝试了什么。如果您进行了一些尝试,您应该分享它们以及任何错误消息。
-
我认为不需要 id,因为这些元素仍然可以通过索引
document.getElementById('contenu').childNodes[index]访问 -
@slai 好的,谢谢,实际上是对的,但这只是我更喜欢使用 ID。感谢您的帮助
-
@Alan 我只是尝试通过使用便便来增加我的 divElts 和 id 。我刚刚用setAttribute()犯了一个不注意的错误。而已。谢谢你的帮助。 Mabe 并不完美,我很久没有使用 javascript。
-
那么我建议使用有效的 ID stackoverflow.com/questions/70579/…。在某些情况下使用数字作为 id 有效,但在其他情况下无效
标签: javascript object increment