值得一看
广告
彩虹云商城
广告

热门广告位

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

使用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>
<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
相关标签:

css javascript java jquery html js ajax go app ai html文件 JavaScript jquery css html 常量 date 全局变量 字符串 委托 append 事件 dom background table ui

大家都在看:

使用CSS动画实现单张透明图片无限循环滚动效果
解决带滚动条的HTML元素水平对齐偏差:CSS布局实践
在Spring Boot应用中正确配置CSS背景图片路径
使用CSS和JavaScript实现HTML元素抖动效果教程
CSS position: sticky:移动端滚动事件失效问题的优雅解决方案
温馨提示: 本文最后更新于2025-11-07 10:56:21,某些文章具有时效性,若有错误或已失效,请在下方留言或联系在线客服
文章版权声明 1 本网站名称: 创客网
2 本站永久网址:https://new.ie310.com
1 本文采用非商业性使用-相同方式共享 4.0 国际许可协议[CC BY-NC-SA]进行授权
2 本站所有内容仅供参考,分享出来是为了可以给大家提供新的思路。
3 互联网转载资源会有一些其他联系方式,请大家不要盲目相信,被骗本站概不负责!
4 本网站只做项目揭秘,无法一对一教学指导,每篇文章内都含项目全套的教程讲解,请仔细阅读。
5 本站分享的所有平台仅供展示,本站不对平台真实性负责,站长建议大家自己根据项目关键词自己选择平台。
6 因为文章发布时间和您阅读文章时间存在时间差,所以有些项目红利期可能已经过了,能不能赚钱需要自己判断。
7 本网站仅做资源分享,不做任何收益保障,创业公司上收费几百上千的项目我免费分享出来的,希望大家可以认真学习。
8 本站所有资料均来自互联网公开分享,并不代表本站立场,如不慎侵犯到您的版权利益,请联系79283999@qq.com删除。

本站资料仅供学习交流使用请勿商业运营,严禁从事违法,侵权等任何非法活动,否则后果自负!
THE END
喜欢就支持一下吧
点赞7赞赏 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容