使用JavaScript创建表

时间:2018-12-21 06:49:32

标签: javascript arrays dom html-table

我应该使用JavaScript从头开始创建一个这样的表,但我不知道该如何做。

我应该为此使用数组吗?

我还是JavaScript的新手,这是我学习JavaScript的第一周。感谢您的帮助!

BMI                   Health category

Below 18.5            Under weight

Between 18.5 and 23   Normal weight

Between 23 and 27.5   Over weight

Above 27.5            Obese

1 个答案:

答案 0 :(得分:-1)

在Pure JS中创建表:

var table_header = ['BMI', 'Health category'];
var table_rows = [
    ['Below 18.5', 'Under weight'],['Between 18.5 and 23', 'Normal weight'], 
    ['Between 23 and 27.5', 'Over weight'],['Above 27.5', 'Obese']
];

var dom_body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
var tbody = document.createElement('tbody');

//use for loop to add row and cells into the table body
var tr = document.createElement('tr');
table_header.forEach(function(value,index){
   var td = document.createElement('td'); //table cell
   td.innerHTML= value; //set cell value
   tr.appendChild(td); //add it into row
})

tbody.appendChild(tr); //add table header

//insert table rows
table_rows.forEach(function(row,index){
   var tr = document.createElement('tr');

   //append cells for this current row
   row.forEach(function(value,index){
       var td = document.createElement('td'); //table cell
       td.innerHTML= value; //set cell value
           tr.appendChild(td); //add it into row
   })

   tbody.appendChild(tr); //add row
})


//add the table in the dom 
table.appendChild(tbody);
dom_body.appendChild(table);