简体   繁体   English

使用 JavaScript 创建表格

[英]Using JavaScript to create a table

I'm supposed to create a table like this from scratch using JavaScript and I have no idea how.我应该使用 JavaScript 从头开始​​创建一个这样的表,但我不知道如何。

Am I supposed to use array for this?我应该为此使用数组吗?

I'm still new to JavaScript and this is my first week of learning it.我还是 JavaScript 的新手,这是我学习它的第一周。 Thanks for the help!谢谢您的帮助!

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

Creating table in Pure JS:在纯 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM