我可能正在思考这个问题,但如何重启计数器呢?此外,正如您将在我的代码中看到的那样,计数器应该匹配,但不是。我希望单元格具有它所在行的共享值,例如第一行单元格应该具有ID:cell 0.0,cell 0.1,而是跳过第一个数字是前一行的一个。
var rowCount = 0;
var cellCount = 0;
function appendRow(id, style) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
row.setAttribute('id', style);
var i;
row.id = 'row' + rowCount;
rowCount++
console.log(rowCount, cellCount);
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
cellCount++
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
&#13;
table {
text-align: center;
}
td {
width: 100px;
}
&#13;
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
</div>
&#13;
答案 0 :(得分:1)
我不确定这是你想要的,但是如果你把rowCount++
放在for循环之后它从第一个元素开始,那么从那里开始增加。
如果您希望单元重新开始,请将createCell更改为使用i而不是cellCount:
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);