【发布时间】:2016-12-23 13:41:49
【问题描述】:
我正在尝试编写一个构造函数,其方法是循环多行(数字参数),然后对于每个单独的行循环多个点(数字参数)。在这两个循环中的每一个中,都会呈现 html 的一部分。我可以让第一部分 html 呈现,但是当我尝试使用来自先前呈现的 html 的选择器循环第二部分时,什么也没有发生。我错过了什么?
HTML 代码
<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;
}
}
};
解决方案(仅限javascript)
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;
};
感谢@rainerh 给了我问题的答案。在考虑了@shilly 在评论中关于在 for 循环中使用.innerHTML 所说的话之后,我对我的代码进行了一些更改以反映他的建议。希望这对其他尝试做类似我的事情的人有用。
【问题讨论】:
-
getElementsByClassName正在返回一个元素数组。所以innerHTML不起作用。您必须遍历返回的元素。 -
旁注:尽量避免在循环中设置innerHTML。将所有元素附加到一个字符串并在字符串完成后执行一个 innerHTML。这将大大增加渲染时间,因为您获得了很多行。
-
@Shilly,感谢您的建议,我在问题中添加了一个修改后的代码示例以反映您的评论,当然它可以满足我的需求。
标签: javascript loops constructor prototype selector