【问题标题】:How increment "id" Object with js?如何用 js 增加“id”对象?
【发布时间】: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;
}
&lt;div id="contenu"&gt;&lt;/div&gt;

谢谢

【问题讨论】:

  • 从您的代码中不清楚您尝试了什么。如果您进行了一些尝试,您应该分享它们以及任何错误消息。
  • 我认为不需要 id,因为这些元素仍然可以通过索引 document.getElementById('contenu').childNodes[index] 访问
  • @slai 好的,谢谢,实际上是对的,但这只是我更喜欢使用 ID。感谢您的帮助
  • @Alan 我只是尝试通过使用便便来增加我的 divElts 和 id 。我刚刚用setAttribute()犯了一个不注意的错误。而已。谢谢你的帮助。 Mabe 并不完美,我很久没有使用 javascript。
  • 那么我建议使用有效的 ID stackoverflow.com/questions/70579/…。在某些情况下使用数字作为 id 有效,但在其他情况下无效

标签: javascript object increment


【解决方案1】:

我排错了

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();

【讨论】:

    【解决方案2】:

    setAttribute 是一种方法——你不能用等号给它赋值。对您的代码稍作更正即可解决问题:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 谢谢我的错误,它在 divElts.setAttribute() 中,没有 =。感谢您的帮助
      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 2014-09-10
      • 2016-12-06
      • 2014-11-30
      • 2018-07-26
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多