如何增加" id"用js对象?

时间:2017-12-24 18:08:41

标签: javascript object increment

感谢您的帮助。这是我的第一个带有对象的小项目,而且很难。

我用Object创建了一个板,但我想增加#34; ID"对于我创建的每个divElts。 你能救我吗?



  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();
&#13;
#contenu{
  width :440px;
  height:440px;
}
.case{
  border-radius:20px;
  border:solid black 1px;
  display:inline-block;
  width:200px;
  height:200px;
   background-color:yellow;
}
&#13;
<div id="contenu"></div>
&#13;
&#13;
&#13;

由于

3 个答案:

答案 0 :(得分:0)

我在行中有错误

close()

更改它
divElts.setAttribute = ('id', this.id++);

这是优化版

divElts.setAttribute('id', this.id++);

答案 1 :(得分:0)

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();是一种方法 - 您不使用equals为其赋值。对代码进行小的修正将解决它:

setAttribute
  

MDN文档:Element.setAttribute(name, value);

答案 2 :(得分:-1)

您可以使用javascript方法长度在html中找到od div元素“contenu”的数字来执行此操作:

var incremented_id = document.querySelectorAll('.contenu').length + 1;
divElts.setAttribute('id', incremented_id);