欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JavaScript创建表格的方法

时间:2021-01-09 11:15:15|栏目:JavaScript代码|点击:

本文实例为大家分享了JavaScript创建表格的具体代码,供大家参考,具体内容如下

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>

</head>
<body>
<div id = "mountains"></div>

<script>
 let MOUNTAINS = [
  {name: "Kilimanjaro", height: 5895, place: "Tanzania"},
  {name: "Everest", height: 8848, place: "Nepal"},
  {name: "Mount Fuji", height: 3776, place: "Japan"},
  {name: "Vaalserberg", height: 323, place: "Netherlands"},
  {name: "Denali", height: 6168, place: "United States"},
  {name: "Popocatepetl", height: 5465, place: "Mexico"},
  {name: "Mont Blanc", height: 4808, place: "Italy/France"}
 ];

 // 创建表格
 function buildTable(data) {
  let table = document.createElement("table");
  let tr = document.createElement("tr");
  // 通过 for in 循环遍历对象,得到对象的属性,为表头添加内容
  for (let i in data[6]) {
   let th = document.createElement("th");
   th.innerText = i;
   tr.appendChild(th);
  }
  table.appendChild(tr);
  // 通过 forEach 循环遍历对象数组,为表格添加行
  data.forEach((value, index) => {
   let tr = document.createElement("tr");
   // 通过 for in 循环遍历对象,得到对象的属性,给每行添加内容
   for (let index1 in data[index]) {
    let td = document.createElement("td");
    td.innerText = data[index][index1];
    tr.appendChild(td);
   }
   table.appendChild(tr);
  });
  //设置表格的对齐属性,和边框属性
  table.setAttribute("text-align", "right");
  table.setAttribute("border","1");

  return table;
 }

 document.querySelector("div").appendChild(buildTable(MOUNTAINS));
</script>
</body>
</html>

上一篇:JavaScript 键盘event.keyCode值列表大全

栏    目:JavaScript代码

下一篇:js自带函数备忘 数组

本文标题:JavaScript创建表格的方法

本文地址:http://www.codeinn.net/misctech/42686.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有