如何仅使用Array中的值填充偶数单元格并在每个奇数单元格中插入单个元素?
//I have an Array with following values :
let Array = [1, 2, 3, 4, 5];
//And HTML Element :
let Element = "<span> Some Element </span>"
// I create a table with cells = length of elements * 2
let newTable = document.createElement("table");
newTable.id = "tableID";
let row = [];
for (let i = 0; i < Array.length * 2; i++) {
row[i] = newTable.insertRow(i);
}
如何使用数组中的数字填充表格甚至单元格 - 0 2 4 6 8并将HTMLElement放在它们之间?
答案 0 :(得分:1)
此代码与您的代码非常相似,只是在每行添加一个单元格,然后根据条件i%2
修改单元格的内容:
//I have an Array with following values :
let Array = [1, 2, 3, 4, 5];
//And HTML Element :
let Element = "<span> Some Element </span>"
// I create a table with cells = length of elements * 2
let newTable = document.createElement("table");
newTable.id = "tableID";
document.body.appendChild(newTable);
let row = [];
for (let i = 0; i < Array.length * 2; i++) {
row[i] = newTable.insertRow(-1).insertCell(0);
if (i % 2 == 0)
row[i].innerHTML = i;
else
row[i].innerHTML = Element;
}
td {
border: 1px solid black;
}
答案 1 :(得分:1)
只需添加一个支票或者不是你甚至(i%2 === 0)会这样做,然后决定你想要添加什么
//I have an Array with following values :
let array = [1, 2, 3, 4, 5];
//And HTML Element :
let element = "<span> Some Element </span>";
// I create a table with cells = length of elements * 2
let newTable = document.createElement("table");
newTable.id = "tableID";
let row = [];
for (let i = 0; i < array.length * 2; i++) {
row[i] = newTable.insertRow();
let cell = row[i].insertCell();
if (i%2 === 0) {
cell.appendChild( document.createTextNode( array[i/2] ) );
} else {
cell.appendChild( document.createTextNode( element ) );
}
}
document.getElementById('container').appendChild( newTable );
&#13;
<div id="container">
</div>
&#13;
答案 2 :(得分:0)
从您的代码中可以做到:
let j=0;
for (let i = 0; i < Array.length; i++) {
row[j++] = newTable.insertRow(i);
row[j++] = newTable.insertRow(Element);
}