Dynamic creation of table with DOM

前端 未结 9 1064
面向向阳花
面向向阳花 2020-11-28 06:07

Can someone tell me what\'s wrong with this code? I want to create a table with 2 columns and 3 rows, and in the cells I want Text1 and Text2 on every row. This code creates

9条回答
  •  一生所求
    2020-11-28 06:47

    You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.

    Edit: Revise your code like so:

    for (var i = 1; i < 4; i++)
    {
       tr[i] = document.createElement('tr');   
          var td1 = document.createElement('td');
          var td2 = document.createElement('td');
          td1.appendChild(document.createTextNode('Text1'));
          td2.appendChild(document.createTextNode('Text2'));
          tr[i].appendChild(td1);
          tr[i].appendChild(td2);
      table.appendChild(tr[i]);
    }
    

提交回复
热议问题