使用JavaScript和jQuery实现动态表格生成、随机着色与数量控制

花韻仙語
发布: 2025-11-07 10:37:16
原创
840人浏览过

使用javascript和jquery实现动态表格生成、随机着色与数量控制

本教程旨在详细指导如何利用JavaScript和jQuery实现动态生成HTML表格的功能,并为每个新生成的表格应用随机背景颜色。此外,文章还将介绍如何设置一个最大生成数量限制,以避免无限制的DOM元素创建。通过本教程,开发者将掌握动态UI元素管理、样式个性化以及交互逻辑控制的关键技术,从而提升网页应用的灵活性和用户体验。

动态表格生成、随机着色与数量控制教程

在现代Web开发中,动态生成和管理页面元素是常见的需求,例如根据用户操作添加新的数据行、表单或卡片。本教程将深入探讨如何结合JavaScript和jQuery实现以下功能:

  1. 动态生成表格: 在用户点击按钮时,向页面中追加新的HTML表格。
  2. 随机背景着色: 为每个新生成的表格应用独特的随机背景颜色,增加视觉多样性。
  3. 数量限制: 设置一个最大生成数量,防止用户无限次地生成表格,优化页面性能和用户体验。

1. HTML结构准备

首先,我们需要一个基础的HTML结构来承载我们的动态内容。这包括一个触发表格生成的按钮和一个用于容纳动态表格的容器。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态表格示例</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .container {
            margin-top: 20px;
            width: 80%;
            max-width: 800px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .dynamic-form {
            margin-bottom: 15px;
            margin-top: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            position: relative;
        }
        .dynamic-form table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .dynamic-form table td {
            padding: 8px;
            border: 1px solid #eee;
            vertical-align: top;
        }
        .dynamic-form input[type="text"] {
            width: calc(100% - 10px);
            padding: 5px;
            margin-left: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        .remove-btn {
            float: right;
            margin-right: 10px;
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .add-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .message {
            color: #dc3545;
            margin-top: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>动态表格管理</h2>
        <label for="locationInput">位置:</label>
        <input type="text" id="locationInput" name="locationInput">
        <button type="button" id="addTableButton" class="add-btn">+</button>
        <div id="dynamic-forms">
            <!-- 动态生成的表格将在此处显示 -->
        </div>
        <p id="limitMessage" class="message"></p>
    </div>

    <script>
        // JavaScript/jQuery 代码将在此处添加
    </script>
</body>
</html>
登录后复制

在上述HTML中:

立即学习Java免费学习笔记(深入)”;

  • 我们引入了jQuery库。
  • #locationInput 是一个文本输入框,其值可以用于填充动态表格中的某个字段。
  • #addTableButton 是触发表格生成的按钮。
  • #dynamic-forms 是一个容器,所有动态生成的表格都将被追加到这个 div 中。
  • #limitMessage 用于显示达到数量限制时的提示信息。
  • CSS样式用于美化页面和动态生成的表格。

2. 实现表格的动态生成与随机着色

接下来,我们将编写JavaScript代码来实现表格的动态生成,并为每个表格设置一个随机的背景颜色。

飞书多维表格
飞书多维表格

表格形态的AI工作流搭建工具,支持批量化的AI创作与分析任务,接入DeepSeek R1满血版

飞书多维表格 26
查看详情 飞书多维表格

2.1 随机颜色生成函数

为了实现随机着色,我们需要一个函数来生成随机的RGB颜色值。

/**
 * 生成一个随机的RGB颜色字符串。
 * @returns {string} 例如 "rgb(255, 100, 50)"
 */
function getRandomColor() {
    const r = Math.floor(Math.random() * 200) + 50; // 避免过暗或过亮的颜色
    const g = Math.floor(Math.random() * 200) + 50;
    const b = Math.floor(Math.random() * 200) + 50;
    return `rgb(${r}, ${g}, ${b})`;
}
登录后复制

这个 getRandomColor 函数会生成一个RGB颜色字符串,其中每个颜色分量(红、绿、蓝)的取值范围被限制在50到249之间,以确保生成的颜色既不太暗也不太亮,从而保证文本的可读性。

2.2 动态生成表格逻辑

现在,我们将把随机颜色生成函数整合到按钮的点击事件中,实现动态表格的追加。

$(document).ready(function () {
    let tableCount = 0; // 用于追踪已生成的表格数量
    const MAX_TABLES = 3; // 设置最大允许生成的表格数量

    $("#addTableButton").click(function () {
        if (tableCount >= MAX_TABLES) {
            $("#limitMessage").text(`已达到最大表格数量限制 (${MAX_TABLES})。`);
            return; // 阻止继续生成表格
        }

        $("#limitMessage").text(""); // 清除之前的提示信息

        const currentColor = getRandomColor(); // 获取一个随机颜色
        const locationValue = $("#locationInput").val(); // 获取位置输入框的值
        const uniqueFormId = `form_${Date.now()}_${tableCount}`; // 为每个表单生成唯一ID

        $("#dynamic-forms").append(
            `
            <form id="${uniqueFormId}" class="dynamic-form">
                <button type="button" class="remove-btn" data-target-form="${uniqueFormId}">-</button>
                <table style="background-color: ${currentColor};">
                    <tr>
                        <td>位置: <input type="text" value="${locationValue}"></td>
                        <td>P1: <input type="text"></td>
                    </tr>
                    <tr>
                        <td>P2: <input type="text"></td>
                        <td>P3: <input type="text"></td>
                    </tr>
                    <tr>
                        <td>Sometime: <input type="text"></td>
                        <td>Full day: <input type="text"></td>
                    </tr>
                </table>
            </form>
            `
        );

        $("#locationInput").val(""); // 清空位置输入框
        tableCount++; // 增加表格计数

        // 为新添加的移除按钮绑定事件
        $(`.remove-btn[data-target-form="${uniqueFormId}"]`).on("click", function() {
            const targetId = $(this).data("target-form");
            $(`#${targetId}`).remove();
            tableCount--; // 减少表格计数
            $("#limitMessage").text(""); // 清除提示信息
        });
    });
});
登录后复制

代码解析:

  • tableCount:一个全局变量,用于记录当前已生成的表格数量。
  • MAX_TABLES:常量,定义了允许生成的最大表格数量。
  • 在 $("#addTableButton").click() 事件处理函数中:
    • 首先检查 tableCount 是否已达到 MAX_TABLES。如果达到,则显示提示信息并 return,阻止进一步操作。
    • 调用 getRandomColor() 获取随机背景色。
    • 获取 locationInput 的当前值,并将其填充到新表格的“位置”字段中。
    • 使用模板字符串构建新的 form 元素,其中包含一个 table。table 的 background-color 属性被设置为 currentColor。
    • 为了确保每个动态生成的表单都有唯一的ID,我们使用了 Date.now() 和 tableCount 组合生成 uniqueFormId。
    • 将生成的HTML字符串通过 $("#dynamic-forms").append() 方法添加到页面中。
    • 清空 locationInput。
    • tableCount 递增。
    • 移除功能: 为每个新添加的 - 按钮(remove-btn)绑定点击事件。当点击时,它会根据 data-target-form 属性找到对应的 form 元素并将其从DOM中移除,同时 tableCount 递减,并清除任何限制消息。这里使用了事件委托的变体,直接为新元素绑定事件,因为新元素是动态创建的。

3. 完整示例代码

将所有代码整合到HTML文件中,形成一个完整的可运行示例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态表格示例</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .container {
            margin-top: 20px;
            width: 80%;
            max-width: 800px;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .dynamic-form {
            margin-bottom: 15px;
            margin-top: 15px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            position: relative;
        }
        .dynamic-form table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .dynamic-form table td {
            padding: 8px;
            border: 1px solid #eee;
            vertical-align: top;
        }
        .dynamic-form input[type="text"] {
            width: calc(100% - 10px);
            padding: 5px;
            margin-left: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }
        .remove-btn {
            float: right;
            margin-right: 10px;
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .add-btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .message {
            color: #dc3545;
            margin-top: 10px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>动态表格管理</h2>
        <label for="locationInput">位置:</label>
        <input type="text" id="locationInput" name="locationInput">
        <button type="button" id="addTableButton" class="add-btn">+</button>
        <div id="dynamic-forms">
            <!-- 动态生成的表格将在此处显示 -->
        </div>
        <p id="limitMessage" class="message"></p>
    </div>

    <script>
        /**
         * 生成一个随机的RGB颜色字符串。
         * @returns {string} 例如 "rgb(255, 100, 50)"
         */
        function getRandomColor() {
            const r = Math.floor(Math.random() * 200) + 50; // 避免过暗或过亮的颜色
            const g = Math.floor(Math.random() * 200) + 50;
            const b = Math.floor(Math.random() * 200) + 50;
            return `rgb(${r}, ${g}, ${b})`;
        }

        $(document).ready(function () {
            let tableCount = 0; // 用于追踪已生成的表格数量
            const MAX_TABLES = 3; // 设置最大允许生成的表格数量

            $("#addTableButton").click(function () {
                if (tableCount >= MAX_TABLES) {
                    $("#limitMessage").text(`已达到最大表格数量限制 (${MAX_TABLES})。`);
                    return; // 阻止继续生成表格
                }

                $("#limitMessage").text(""); // 清除之前的提示信息

                const currentColor = getRandomColor(); // 获取一个随机颜色
                const locationValue = $("#locationInput").val(); // 获取位置输入框的值
                const uniqueFormId = `form_${Date.now()}_${tableCount}`; // 为每个表单生成唯一ID

                $("#dynamic-forms").append(
                    `
                    <form id="${uniqueFormId}" class="dynamic-form">
                        <button type="button" class="remove-btn" data-target-form="${uniqueFormId}">-</button>
                        <table style
登录后复制

以上就是使用JavaScript和jQuery实现动态表格生成、随机着色与数量控制的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号