【问题标题】:JavaScript Cell Does not Match RowJavaScript 单元格不匹配行
【发布时间】:2017-11-15 15:36:14
【问题描述】:

我有一个表,用户可以在其中添加客户,当添加客户时,会为行和行中的每个单元格分配一个唯一的 ID。

如您所见,当您添加一行时,我记录了 row.idcell.id,但是,cell.id 应该是 'cell_' + rowCount + '_' + i,但单元格中的 rowCount 与一排。

// add customer or item
// append row to the HTML table
var rowCount = 1;
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++
  // insert table cells to the new row
  for (i = 0; i < table.rows[0].cells.length; i++) {
    createCell(row.insertCell(i), i, 'cell_' + rowCount + '.' + i); // starts over when 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
  console.log(row.id + ' ' + div.id);
}
table {
  text-align: center;
}
td  {
  width: 100px; 
}

tr:nth-child(even) {
  background-color: #fff;
}
tr:nth-child(odd) {
  background-color: #eee;
}
<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>Work #</td>
      <td>Cell #</td>
      <td style="border-top-right-radius: 5px;">Main Location</td>
    </tr>
  </table>
  <table id="custList" contenteditable="true">
    <tr>
      <td>Someone</td>
      <td>903-636-0000</td>
      <td>903-626-0000</td>
      <td>something</td>
    </tr>
  </table>
</div>

【问题讨论】:

    标签: javascript function html-table counter


    【解决方案1】:

    你有 row.id = 'row' + rowCount; rowCount++

    紧随其后

    'cell_' + rowCount

    您首先在设置为 1 的行上使用 rowCount,然后将其设置为 2,然后在设置为 2 时在单元格上使用它。

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2019-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 2017-05-21
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多