JavaScript - 迭代动态创建html

时间:2016-12-23 13:41:49

标签: javascript loops constructor prototype selector

我正在尝试使用循环多个行(数字参数)的方法编写构造函数,然后为每个单独的行循环遍历多个点(数字参数)。在两个循环中的每一个循环中,将呈现一部分html。我可以得到第一部分html渲染,但当我尝试使用先前渲染的html中的选择器循环第二部分没有任何反应。我错过了什么?

HTML CODE

public

JAVASCRIPT CODE

<div class="container">
   <h1 class="heading">Random Colors</h1>
   <div class="row">
       <div id="frame" class="col-xs-12">
           <!-- CONTENT PUSHED BY JAVASCRIPT -->     
       </div>  
   </div><!-- Ends .row -->  
</div><!-- Ends .container -->

解决方案(仅限javascript)

var ColorDots = function(rows, dots) {
    this.numOfRows = rows;
    this.numOfDots = dots;
    this.renderDots();

};

ColorDots.prototype.renderDots = function() { 

    this.rowTemplate = '<div class="color-dot row"></div>';
    this.iconTemplate = '<i class="fa fa-circle icon" aria-hidden="true"></i>';     

    for ( var r = 0; r < this.numOfRows; r++) {

        document.getElementById('frame').innerHTML += this.rowTemplate;

        for ( var i = 0; i < this.numOfDots; i++) {

            document.getElementsByClassName('color-dot').innerHTML += this.iconTemplate;
        }            
    }    
};

谢谢@rainerh给我回答我的问题。在考虑@shilly在评论中关于在for循环中使用 var ColorDots = function(rows, dots) { // Properties this.numOfDots = dots; this.numOfRows = rows || 1; this.iconHtml = '<i class="fa fa-circle icon" aria-hidden="true"></i>'; this.renderRows(); }; ColorDots.prototype.renderRows = function() { this.rowHtml = ''; for ( var r = 0; r < this.numOfRows; r++) { this.rowHtml += '<div class="color-dot row">'; for ( var i = 0; i < this.numOfDots; i++) { this.rowHtml += this.iconHtml; } this.rowHtml += '</div>'; } document.getElementById('frame').innerHTML = this.rowHtml; }; 的内容后,我对代码进行了一些更改以反映他的建议。希望这对其他尝试做类似于我的事情有用。

1 个答案:

答案 0 :(得分:2)

首先,css类是彩色点,而不是你选择器中的彩色点。

其次getElementsByCLassName返回一个数组。所以必须在这里使用索引。

ColorDots.prototype.renderDots = function() { 
  this.rowTemplate = '<div class="color-dot row"></div>';
  this.iconTemplate = '<i class="fa fa-circle icon" aria-hidden="true"></i>';     

  for ( var r = 0; r < this.numOfRows; r++) {

    document.getElementById('frame').innerHTML += this.rowTemplate;
    for ( var i = 0; i < this.numOfDots; i++) {
      document.getElementsByClassName('color-dots')[r].innerHTML += this.iconTemplate;
    }            
  }    
};
相关问题