我创建了一个表,该表似乎运行良好,但是在为该表分配ID,计算其有多少行以及为每行分配ID时遇到了问题。调试器说:


  TypeError:document.getElementById(...)为null


我不知道我做错了什么。有人可以帮忙吗?我也在以下代码中评论了我的问题:

function populateTable(list){
    var tableContent = "<table>";
    for (var i = 0; i < list.length; ++i) {
          var record = list[i];
        tableContent += "<tr><td>" + record.Title + "</td></tr>\n";
    }
tableContent += "</table>";
tableContent.id="orders";
var rows = document.getElementById("orders").rows.length;//why is this null?
document.getElementById("test").innerHTML = rows;
   for (var i=0; i< rows; ++i){
           //how do I assign an id for the element here?
   }
}

最佳答案

您可以通过以下方式执行此操作:

HTML:

<div id="here"> </div> <!-- the table will be added in this div -->


JavaScript:

function populateTable(list){
    var tableContent = document.createElement('table');
    for (var i = 0; i < list.length; ++i) {
        var record = list[i];
        var cell = document.createElement('td');
        var row = document.createElement('tr');
        var textnode = document.createTextNode(record.Title);
        cell.appendChild(textnode);
        row.appendChild(cell);
        tableContent.appendChild(row);
    }
    tableContent.id="orders";
    document.getElementById("here").appendChild(tableContent);  // the table is added to the HTML div element
    var rows = document.getElementById("orders").rows;
    for (var i=0; i < rows.length; ++i){
        rows[i].id = "myId" + (i+1);  // this is how you assign IDs
        console.log(rows[i]);
    }

}

var persons = [{Title:"John"}, {Title:"Marry"}];
populateTable(persons);

07-24 16:55