我是JavaScript的新手,想知道如何从JavaScript数组中填充div表。 div表如下所示:
<div id="palette" style="border: solid 1px black; width: 100%; height: 100%;">
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
</div>
数组是一维的,包含字符串。数组中的每个字符串都应该位于div-table中的特定单元格中。
答案 0 :(得分:1)
仅使用Javascript(使用jQuery可能更容易),您可以执行以下操作:
.getElementById()
访问包含元素.getElementsByClassName()
访问子元素.innerText
写入所选元素。这是一个如何操作的工作示例:
var arr = ['Adam','Bruce','Clive','Don','Evan','Francis', 'Glenn', 'Henry', 'Ivan', 'Jade', 'Ken', 'Logan', 'Mario', 'Nathan', 'Omar', 'Quentin', 'Peter', 'Roman'];
var palette = document.getElementById("palette");
var rows = palette.getElementsByClassName("divTableRow");
var counter = 0;
for (var row of rows) {
var cells = row.getElementsByClassName("divTableCell");
for (var cell of cells) {
cell.innerText = arr[counter];
counter++;
};
};
#palette {
border: none;
display: table;
}
.divTableRow {
width: 100%;
display: table-row;
}
.divTableCell {
width: 28%;
padding: 1%;
border: 1px solid #000;
display: table-cell;
}
<div id="palette" style="border: solid 1px black; width: 100%; height: 100%;">
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
<div class="divTableRow">
<div class="divTableCell"></div>
<div class="divTableCell"></div>
<div class="divTableCell"></div>
</div>
</div>