【问题标题】:JavaScript Restart CounterJavaScript 重启计数器
【发布时间】:2017-11-13 20:00:13
【问题描述】:

我可能想多了这个问题,但是如何重新启动计数器?此外,正如您将在我的代码中看到的那样,计数器应该匹配但不匹配。我希望单元格具有它所在行的共享值,例如第一行单元格应该具有 ID:单元格 0.0,单元格 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
}
table {
  text-align: center;
}
td {
  width: 100px;
}
<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>

【问题讨论】:

  • 您的单元格计数器的速度是原来的两倍,因为表格中的单元格数量是行数的两倍。

标签: javascript html function counter


【解决方案1】:

我不确定这是否是您想要的,但如果您将 rowCount++ 放在 for 循环之后,它将从 0 处的第一个元素开始,然后从那里递增。

如果您希望单元格重新开始,请将 createCell 更改为使用 i 而不是 cellCount:

createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多