首页 > 解决方案 > 如何在Javascript中从表中删除最后一个标题

问题描述

我编写了一个代码来加载数据,添加和删除附加列。但是我无法删除最后一个标题(附加列)。我设法弄清楚删除第一列标题。请参阅测试功能。有没有办法删除一个单元格标题或删除带有标题的列?命令

   tbl.removeChild(tbl.firstChild); 

仅删除第一列的第一个标题。然而,代码

 tbl.removeChild(tbl.lastChild);

删除所有数据,而不是最后附加列的最后一个标题。我在这里缺少什么?更新:我设法删除了最后一个标题,但只删除了一次,下一个最后一列被删除但标题保留。尽管如此,我仍然无法解决故障。我修改的代码被标记

下面是完整的代码,

var flag1 = false;
var file = document.getElementById('inputfile');
var txtArr = [];

if (typeof(document.getElementsByTagName("table")[0]) != "undefined") {
  document.getElementsByTagName("table")[0].remove();
}
// get the reference for the body
var body = document.getElementsByTagName("body")[0];

// creates a <table> element and a <tbody> element
var tbl = document.createElement("table"),
  thead = document.createElement('thead');
var tblBody = document.createElement("tbody");

file.addEventListener('change', () => {
  var fr = new FileReader();
  fr.onload = function() {
    // By lines
    var lines = this.result.split('\n');
    for (var line = 0; line < lines.length; line++) {
      txtArr.push(lines[line].split(" "));
    }
  }
  fr.readAsText(file.files[0]);
});

//console.log(flag1);
// document.getElementById('output').textContent=txtArr.join("");
//document.getElementById("output").innerHTML = txtArr[0]; 
// console.log(txtArr[2]); 

function generate_table() {
  // creating all cells
  if (flag1 == false) {
    th = document.createElement('th'),
      th.innerHTML = "Name";
    tbl.appendChild(th);
    th = document.createElement('th');
    th.innerHTML = "Sample1";
    tbl.appendChild(th);
    tbl.appendChild(thead);
    tbl.appendChild(tblBody);
  } //endif flag1=false
  else {
    th = document.createElement('th');
    th.innerHTML = "Sample2";
    tbl.appendChild(th);
    tbl.appendChild(thead);
    tbl.appendChild(tblBody);
  }

  for (var i = 0; i < txtArr.length - 1; i++) {
    // creates a table row
    var row = document.createElement("tr");
    for (var j = 0; j < 2; j++) {
      var cell = document.createElement("td");
      var cellText = document.createTextNode(txtArr[i][j]);
      cell.appendChild(cellText);
      row.appendChild(cell);
      tblBody.appendChild(row);
    }
    flag1 = true;
    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <body>
    body.appendChild(tbl);
    // sets the border attribute of tbl to 2;
    tbl.setAttribute("border", "2");

  }
  txtArr = [];
}

/////////// testing problems here /////////////////////
function testing() {
  var i;
  var lastCol = tbl.rows[0].cells.length - 1,
    i, j;
  // delete cells with index greater then 0 (for each row)
  console.log(tbl.rows.length);

  //while (tbl.hasChildNodes()) {
  // tbl.removeChild(tbl.lastChild); // this line does not remove the last header
  //}

  for (i = 0; i < tbl.rows.length; i++) {
    for (j = lastCol; j > lastCol - 1; j--) {
      tbl.rows[i].deleteCell(j);
    }
  }
  tbl.removeChild(thead);  // this was updated
  tbl.removeChild(th);     // this was updated
 // tbl.removeChild(tbl.firstChild); // this code remove only the first header
}
/////////// end of testing ////////////////////////////

function appendColumn() {
  var i;

  th = document.createElement('th');
  th.innerHTML = "Sample";
  tbl.appendChild(th);
  tbl.appendChild(thead);
  tbl.appendChild(tblBody);
  // open loop for each row and append cell
  for (i = 0; i < tbl.rows.length; i++) {
    createCell(tbl.rows[i].insertCell(tbl.rows[i].cells.length), i, 'col');
  }
}

// create DIV element and append to the table cell
function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode(text); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('class', style); // set DIV class attribute
  div.setAttribute('className', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}

// delete table column with index greater then 0
function deleteColumn() {
  var lastCol = tbl.rows[0].cells.length - 1,
    i, j;
  // delete cells with index greater then 0 (for each row)
  console.log(tbl.rows.length);
  for (i = 0; i < tbl.rows.length; i++) {
    for (j = lastCol; j > lastCol - 1; j--) {
      tbl.rows[i].deleteCell(j);
    }
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta content="utf-8" http-equiv="encoding">
  <title>Read Text File</title>
</head>

<body>
  <input type="file" name="inputfile" id="inputfile">
  <br>
  <pre id="output"></pre>

  <input type="button" value="Generate a table." onclick="generate_table()">
  <input type="button" value="Add column" onclick="appendColumn()">
  <input type="button" value="Delete column" onclick="deleteColumn()">
  <input type="button" value="testing" onclick="testing()">
  <table id="table">
</body>

</html>

标签: javascripthtml-table

解决方案


您可以遍历行并删除每个行的最后一个单元格。

for(const row of tbl.rows){
    row.deleteCell(-1);
}
//or
[...tbl.rows].forEach(row => row.deleteCell(-1));

推荐阅读