Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js table

作者:至尊巅峰   发布日期:2025-11-13   浏览:84

<!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>

解释说明:

  • HTML结构:包含一个表格 (<table>) 和一个标题 (<h2>)。表格有一个 id="myTable",用于在 JavaScript 中引用它。
  • CSS样式:设置了表格的边框、宽度和单元格的内边距及对齐方式。
  • JavaScript代码
    • 获取表格元素 (document.getElementById("myTable"))。
    • 定义了一个数据数组 data,其中包含要插入表格的数据。
    • 使用 for 循环遍历数据数组,并为每一行数据动态创建一个新的表格行 (insertRow) 和单元格 (insertCell)。
    • 最后将数据插入到对应的单元格中。

这个示例展示了如何使用 JavaScript 动态生成 HTML 表格并填充数据。

上一篇:js 给input赋值

下一篇:js <<

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站