代码之家  ›  专栏  ›  技术社区  ›  hannacreed

JavaScript重启计数器

  •  0
  • hannacreed  · 技术社区  · 8 年前

    我可能想得太多了,但如何重新启动计数器?此外,正如您将在我的代码中看到的,计数器应该匹配,但不匹配。我希望单元格具有其所在行的共享值,例如,第一行单元格应具有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>
    1 回复  |  直到 8 年前
        1
  •  1
  •   ShadowCommander user    8 年前

    我不确定这是你想要的,但如果你把 rowCount++ 在for循环之后,它从0开始第一个元素,然后从0开始递增。

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

    createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);
    
    推荐文章