在javascript中动态添加删除和添加表

时间:2017-05-02 15:27:22

标签: javascript

我需要动态创建一个表(包含3个列),从两个下拉列表中选择值并在表的两列中插入。该表可以给出Max 5行。  单击下拉列表旁边的添加链接时会发生动态创建。第三列包含一个链接删除,如果单击则删除该行。

我还需要存储和删除(如果单击删除)列值。

动态创建表时,我创建了一个行ID,即行计数。我这样做是因为虽然删除行计数正在改变但对应于行Id我可以选择列值。

现在的问题是删除了5行中的第3行。我插入一个新行,它的计数为5,行id现在变为5,我的列值替换第5行的原始值。 如何插入新行? 我想不使用jquery

来做

请在此处找到我的代码: -

addRow()
 { 
var myName = document.getElementById("name"); 
var age = document.getElementById("age"); 
var table = document.getElementById("myTableData"); 
var rowCount = table.rows.length; 
var row = table.insertRow(rowCount); row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="deleteRow(this)">'; row.insertCell(1).innerHTML= myName.value; row.insertCell(2).innerHTML= age.value; 
row.id = rowCount;
var testValone= 'colone';
var colVal = testVar + rowCount;
var testValtwo = 'coltwo';
var colValTwo = testValtwo + rowCount; 
// there are 10 global variables storing the col value
//colVal1, colVal2.... colVal5 
//colValTwo1.... colValTwo5
// store the inner HTML values accordingly everytime the function is called.
} 

function deleteRow(obj) 
{ 
var index = obj.parentNode.parentNode.rowIndex;
 var table = document.getElementById("myTableData"); 
var id = obj.parentNode.parentNode.id

var testValone= 'colone';
var colVal = testValone + id;
var testValtwo = 'coltwo';
var colValTwo = testValtwo + id; 
table.deleteRow(index); // issue comes here after deleting when added.
//global variables are set to null.
}⁠⁠⁠⁠

1 个答案:

答案 0 :(得分:0)

您当前的问题是处理/存储数据的方式,您必须通过以下方式查看它:

添加数据时,可以根据当前长度设置行的索引,例如

#0 Row 1
#1 Row 2
#2 Row 3
#3 Row 4

现在删除#3不是问题,然后下一次添加将是正确的,但是,删除#3以外的任何行会导致以下数据结构

#0 Row 1
#2 Row 3
#3 Row 4

之后添加另一行会导致这个复杂的错误视图,例如:

#0 Row 1
#2 Row 3
#3 Row 4
#3 Row 5

您当前的删除操作基于您在添加行时生成的索引的记录。现在您有2个直接解决方案。一种方法是在删除后重新计算以下任何索引,所以如果我从上面获取项目列表,我们可以像这样重新计算

#0 Row 1 
#2 Row 3 -> #1 Row 3
#3 Row 4 -> #2 Row 4

或者,我们可以保留一个数据集,就像一个数组来保存你添加的所有项目,并在添加插入新行时,并在删除时检查数据集中与表中索引相关的索引希望删除。

版本1的代码(更新表中的索引,可能与您的代码最相似)

&#13;
&#13;
function getTable() {
  return document.getElementById('mytable');
}

function addRow() {
  var table = getTable();
  if (!addRow.id) {
    // keep internal id
    addRow.id = 0;
  }
  var id = addRow.id;
  var row = table.insertRow();
  row.insertCell().innerHTML = '#' + id;
  row.insertCell().innerHTML = 'Row ' + id;
  row.insertCell().innerHTML = '<button type="button" onclick="deleteRow(this)">delete</button>';
  row.setAttribute('index', table.rows.length - 1);
  // increase internal id
  addRow.id++;
}

function deleteRow( buttonInRow ) {
  var rowIndex = buttonInRow.parentNode.parentNode.getAttribute('index'), 
      i, table = getTable();
  table.deleteRow( rowIndex );
  for (i = rowIndex; i < table.rows.length; i++) {
    // updates the indexes of the following rows (if any)
    table.rows[i].setAttribute('index', i);
  }
}
&#13;
<button type="button" onclick="addRow()">Add</button>
<table id="mytable" class="table">
<tr class="header"><td>#</td><td>data</td><td></td></tr>
</table>
&#13;
&#13;
&#13;

版本2的代码(将数据保留在表格之外)

&#13;
&#13;
// your global dataset and key
var data = [], id = 0;

function getTable() {
  return document.getElementById('mytable');
}

function addRow() {
  var table = getTable();
  var row = table.insertRow();
  row.insertCell().innerHTML = '#' + id;
  row.insertCell().innerHTML = 'Row ' + id;
  row.insertCell().innerHTML = '<button type="button" onclick="deleteRow(' + id + ')">delete</button>';
  data.push(id); // could theoretically be your full dataset ofcourse
  // increase the id number
  ++id;
}

function deleteRow( idValue ) {
  var table = getTable(),
    index = data.indexOf( idValue ); // if you pushed your full dataset, you need to determine the index in a different way
  // index + 1 because we don't delete the header row, without header row, it would be index
  table.deleteRow( index + 1 ); 
  // remove the row from your datatable
  data.splice( index, 1);
}
&#13;
<button type="button" onclick="addRow()">Add</button>
<table id="mytable">
<tr><td>#</td><td>Data</td><td></td></tr>
</table>
&#13;
&#13;
&#13;

更新前的答案

你可以在这里看到一个基本的例子,id是一个在整个应用程序生命周期中被管理的内部变量,但是你可以动态地添加/删除表中的项目,因为通过表检查表的当前行数。数据数组

我尝试将代码评论为litte;)

&#13;
&#13;
// will be assigned in the onload function
var deleteItem;

// attach to the loading function
window.addEventListener('load', function() {
  // contains the data as objects
  var data = [];
  // contains the internal id
  var _id = 0;
  // gets the elements once, and use them throughout the code
  var template = document.querySelector('#template');
  var newButton = document.querySelector('#btnNew');
  var txtName = document.querySelector('#txtName');
  var txtValue = document.querySelector('#txtValue');
  var rows = document.querySelector('#rows');
  
  // updates the add button to disable/enable
  function updateButtons() {
    if (data.length >= 5) {
      newButton.setAttribute('disabled', true);
    } else {
      newButton.removeAttribute('disabled' );
    }
  }
  
  // removes the data from the text buttons
  function resetForm() {
    txtName.value = '';
    txtValue.value = '';
    updateButtons();
  }
  
  // gets the element from the template filled with the data given
  function getElementFromTemplate( row ) {
    var divElem = template.innerHTML, newElem = document.createElement('div');
    for (var prop in row){
      if (row.hasOwnProperty( prop )) {
        divElem = divElem.split('{ ' + prop + ' }').join( row[prop] );
      }
    }
    newElem.innerHTML = divElem;
    return newElem;
  }
  
  // deletes an item from the ui + data
  deleteItem = (id) => {
    // get the row that got clicked
    var row = document.querySelector('#row-' + id).parentNode, i;
    // removes it from the ui
    rows.removeChild(row);
    // searches the item
    for (i = 0; i < data.length; i++) {
      if (data[i].id === id) {
        break;
      }
    }
    // removes the data from the array at this index
    data.splice(i, 1);
    // calls the form to check if it's valid now to add the buttons
    updateButtons();
  };

  // adds a new item
  newButton.addEventListener('click', function() {
    // create a new data item
    var item = { id: ++_id, name: txtName.value, text: txtValue.value };
    // add it to the data
    data.push( item );
    // add the value to the html
    rows.appendChild( getElementFromTemplate( item ) );
    // and reset the form ( empty texts + handle enable/disable add button)
    resetForm();
  });
});
&#13;
<div id="grid">
  <div id="header">
  <input type="text" id="txtName" />
  <input type="text" id="txtValue" />
  <button type="button" id="btnNew">Add</button>
  </div>
  <div id="rows">
  </div>
</div>
<script type="text/template" id="template">
  <div class="row" id="row-{ id }">
    <div><button type="delete" onclick="deleteItem({ id })">Delete</button></div>
    <div>{ id }</div>
    <div>{ name }</div>
    <div>{ text }</div>
  </div>
</script>
&#13;
&#13;
&#13;