【问题标题】:Why variable tbl defined by document.getElementById('table') returns null?为什么由 document.getElementById('table') 定义的变量 tbl 返回 null?
【发布时间】:2021-02-09 21:20:19
【问题描述】:

我正在尝试使用从文本文件下载的数据(没有用户名的数字)将列附加到现有表。下面是我的代码和输出。

 <!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> 

 <script>

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

 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() 
 {
 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");

  // 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 tbl = document.getElementById('table'),thead = document.createElement('thead'),i;
 var tblBody = document.createElement("tbody");
 for (i = 0; i < tbl.rows.length; i++) {}
  }
  /////////// end of testing ////////////////////////////


  function appendColumn() 
  {   var tbl = document.getElementById("table"),thead = document.createElement('thead'), //     table reference
    i;
   // 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 columns with index greater then 0
   function deleteColumns() {
   //    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.getElementById("table"), // table reference
    lastCol = tbl.rows[0].cells.length - 1,    // set the last column index
    i, j;
// delete cells with index greater then 0 (for each row)
for (i = 0; i < tbl.rows.length; i++) {
    for (j = lastCol; j > 0; j--) {
        tbl.rows[i].deleteCell(j);
    }
  }
  }


   </script>

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

我使用浏览按钮下载带有用户名和成绩的 txt 文件。单击生成表后,输出为,

如果我想从名为 sample2.txt 的新文本文件中添加新等级,它具有相同的名称列表但等级不同。我再次浏览并使用 appendColumn 函数在现有表中创建一个新列。但是,它不起作用。我使用测试按钮解决了这个问题。我发现 tbl 变量在 For 循环中是空的。显然,我在召回现有表 tbl 时做错了。你如何回忆先前已由 generate_table 函数定义的现有变量 tbl?

【问题讨论】:

    标签: arrays function html-table datatable getelementbyid


    【解决方案1】:

    为了使它工作,我通过将此代码行放在行的下方来全局声明 tbl,

      var tbl = document.getElementById('table');
    

    并从每个函数中删除 tbl 声明。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2015-02-02
      相关资源
      最近更新 更多