使用JS编写动态表格

发布于:2025-07-16 ⋅ 阅读:(12) ⋅ 点赞:(0)

JavaScript动态表格生成

引言:动态表格的核心价值

在现代Web开发中,动态生成表格是展示结构化数据的常用技术。通过JavaScript实现表格动态生成不仅提升了用户体验,还降低了数据传输量。本文将通过一个数学计算参考表的案例,详细解析如何高效实现动态表格生成。

实现效果

image-20250715231110196

完整实现代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculation Reference Table</title>
</head>

<body>
    <div class="container">
        <h1>Calculation Reference Table Generator</h1>

        <button class="btn" id="generateBtn">Generate Table</button>

        <div class="table-container">
            <table id="calculationTable">
                <thead>
                    <tr>
                        <th>x</th>
                        <th></th>
                        <th>1/x</th>
                        <th>√x</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Table will be generated here by JavaScript -->
                </tbody>
            </table>
        </div>

        <script>
            document.getElementById('generateBtn').addEventListener('click', generateTable);

            function generateTable() {
                const tableBody = document.querySelector('#calculationTable tbody');
                tableBody.innerHTML = '';

                // Generate table for x values from 1 to 5 in increments of 1
                for (let i = 1; i <= 5; i++) {
                    // Use float representation (1.0, 2.0, etc.) as requested
                    const x = i + 0.0;

                    // Calculate values
                    const square = x ** 2;
                    // Handle reciprocal carefully to avoid floating-point precision issues
                    const reciprocal = (1 / x).toFixed(2);
                    const squareRoot = Math.sqrt(x).toFixed(2);

                    // Create table row
                    const row = document.createElement('tr');

                    // Add cells to row
                    row.innerHTML = `
                    <td>${x.toFixed(1)}</td>
                    <td>${square.toFixed(1)}</td>
                    <td>${reciprocal}</td>
                    <td>${squareRoot}</td>
                `;

                    tableBody.appendChild(row);
                }
            }

            // Generate table on page load
            window.onload = generateTable;
        </script>
</body>

</html>

核心技术深度解析

1. 表结构

  • 标签中为表头部分,这是固定不变的
  • image-20250715231408398
<div class="table-container">
            <table id="calculationTable">
                <thead>
                    <tr>
                        <th>x</th>
                        <th></th>
                        <th>1/x</th>
                        <th>√x</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- Table will be generated here by JavaScript -->
                </tbody>
            </table>
        </div>
  • 标签中是我们需要使用JS代码生成的表格内容
  • image-20250715231542662

2. 生成逻辑

核心功能
  1. 按钮事件监听
    document.getElementById('generateBtn').addEventListener('click', generateTable);
    
    • 当用户点击ID为 generateBtn 的按钮时,触发 generateTable 函数。
  2. 页面加载初始化
    window.onload = generateTable;
    
    • 页面加载完成后自动调用 generateTable,首次生成表格。
generateTable 函数解析
function generateTable() {
    const tableBody = document.querySelector('#calculationTable tbody');
    tableBody.innerHTML = ''; // 清空表格内容

    for (let i = 1; i <= 5; i++) {
        const x = i + 0.0; // 转换为浮点数(如 1.0, 2.0)
        
        // 计算数值
        const square = x ** 2;               // 平方(x²)
        const reciprocal = (1 / x).toFixed(2); // 倒数(1/x),保留2位小数
        const squareRoot = Math.sqrt(x).toFixed(2); // 平方根(√x),保留2位小数

        // 创建表格行
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${x.toFixed(1)}</td>    <!-- x值(保留1位小数)-->
            <td>${square.toFixed(1)}</td> <!-- 平方值 -->
            <td>${reciprocal}</td>       <!-- 倒数 -->
            <td>${squareRoot}</td>       <!-- 平方根 -->
        `;
        tableBody.appendChild(row); // 插入行
    }
}
表格数据逻辑

x1 到 5 的每个值,计算四列数据:

  1. x:原始值(格式化为 x.0,如 1.0
  2. :平方值(如 1.01.0
  3. 1/x:倒数(保留两位小数,如 1/2=0.50
  4. √x:平方根(保留两位小数,如 √2≈1.41

📌 示例输出(前两行)

x 1/x √x
1.0 1.0 1.00 1.00
2.0 4.0 0.50 1.41

关键技术细节
  1. 浮点数处理
    • 通过 x = i + 0.0 将整数转为浮点数(如 11.0)。
    • 使用 .toFixed(N) 控制小数位数(避免浮点精度问题)。
  2. 安全计算
    • 倒数计算 (1/x).toFixed(2):确保结果为两位小数(如 1/3→0.33)。
    • 平方根 Math.sqrt(x).toFixed(2):对无理数截断(如 √2≈1.41)。
  3. DOM操作优化
    • 使用 innerHTML 清空表格(tableBody.innerHTML = '')。
    • 通过模板字符串批量生成表格行(避免多次DOM操作)。
document.getElementById('generateBtn').addEventListener('click', generateTable);

            function generateTable() {
                const tableBody = document.querySelector('#calculationTable tbody');
                tableBody.innerHTML = '';

                // Generate table for x values from 1 to 5 in increments of 1
                for (let i = 1; i <= 5; i++) {
                    // Use float representation (1.0, 2.0, etc.) as requested
                    const x = i + 0.0;

                    // Calculate values
                    const square = x ** 2;
                    // Handle reciprocal carefully to avoid floating-point precision issues
                    const reciprocal = (1 / x).toFixed(2);
                    const squareRoot = Math.sqrt(x).toFixed(2);

                    // Create table row
                    const row = document.createElement('tr');

                    // Add cells to row
                    row.innerHTML = `
                    <td>${x.toFixed(1)}</td>
                    <td>${square.toFixed(1)}</td>
                    <td>${reciprocal}</td>
                    <td>${squareRoot}</td>
                `;

                    tableBody.appendChild(row);
                }
            }

            // Generate table on page load
            window.onload = generateTable;

结语

动态表格生成是Web开发的核心技能,通过本文解析可以看到,即使是简单的数值表也蕴含着深刻的开发原理和实践技巧。掌握这些知识后,您可轻松扩展应用范围至财务系统、科学计算、教育工具等多个领域。


网站公告

今日签到

点亮在社区的每一天
去签到