0

0

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

花韻仙語

花韻仙語

发布时间:2025-11-07 10:37:16

|

882人浏览过

|

来源于php中文网

原创

使用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 驱动的智能语音笔记,随时随地用语音记录你的每一个想法。

下载

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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
jquery插件有哪些
jquery插件有哪些

jquery插件有jQuery UI、jQuery Validate、jQuery DataTables、jQuery Slick、jQuery LazyLoad、jQuery Countdown、jQuery Lightbox、jQuery FullCalendar、jQuery Chosen和jQuery EasyUI等。本专题为大家提供jquery插件相关的文章、下载、课程内容,供大家免费下载体验。

156

2023.09.12

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

337

2023.10.13

jquery删除元素的方法
jquery删除元素的方法

jquery可以通过.remove() 方法、 .detach() 方法、.empty() 方法、.unwrap() 方法、.replaceWith() 方法、.html('') 方法和.hide() 方法来删除元素。更多关于jquery相关的问题,详情请看本专题下面的文章。php中文网欢迎大家前来学习。

406

2023.11.10

jQuery hover()方法的使用
jQuery hover()方法的使用

hover()是jQuery中一个常用的方法,它用于绑定两个事件处理函数,这两个函数将在鼠标指针进入和离开匹配的元素时执行。想了解更多hover()的相关内容,可以阅读本专题下面的文章。

515

2023.12.04

jquery实现分页方法
jquery实现分页方法

在jQuery中实现分页可以使用插件或者自定义实现。想了解更多jquery分页的相关内容,可以阅读本专题下面的文章。

312

2023.12.06

jquery中隐藏元素是什么
jquery中隐藏元素是什么

jquery中隐藏元素是非常重要的一个概念,在使用jquery隐藏元素之前,需要先了解css样式中关于元素隐藏的属性,比如display、visibility、opacity等属性。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

128

2024.02.23

jquery中什么是高亮显示
jquery中什么是高亮显示

jquery中高亮显示是指对页面搜索关键词时进行高亮显示,其实现办法:1、先获取要高亮显示的行,获取搜索的内容,再遍历整行内容,最后添加高亮颜色;2、使用“jquery highlight”高亮插件。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

183

2024.02.23

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

51

2026.01.13

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.9万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 3.6万人学习

CSS教程
CSS教程

共754课时 | 43.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

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