<!DOCTYPE html>
<html>
<head>
<title>JS Table Example</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
th, td {
padding: 15px;
text-align: left;
}
</style>
</head>
<body>
<h2>JavaScript Generated Table</h2>
<table id="myTable">
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
</table>
<script>
// JavaScript code to dynamically add rows to the table
var table = document.getElementById("myTable");
// Data array for table content
var data = [
["John Doe", "30", "Engineer"],
["Jane Smith", "25", "Designer"],
["Jim Brown", "40", "Manager"]
];
// Loop through the data array and add rows to the table
for (var i = 0; i < data.length; i++) {
var row = table.insertRow(i + 1); // Add row after header row
for (var j = 0; j < data[i].length; j++) {
var cell = row.insertCell(j);
cell.innerHTML = data[i][j];
}
}
</script>
</body>
</html>
<table>) 和一个标题 (<h2>)。表格有一个 id="myTable",用于在 JavaScript 中引用它。document.getElementById("myTable"))。data,其中包含要插入表格的数据。for 循环遍历数据数组,并为每一行数据动态创建一个新的表格行 (insertRow) 和单元格 (insertCell)。这个示例展示了如何使用 JavaScript 动态生成 HTML 表格并填充数据。
上一篇:js 给input赋值
下一篇:js <<
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站