HTML动态表单:可编辑表头和增删数据的表单示例
<h2>HTML动态表单:可编辑表头和增删数据的表单示例</h2>
<p>想要创建一个可以自定义表头、添加和删除数据的动态HTML表单?你来对地方了!本文将提供一个完整的示例,包含HTML、CSS和JavaScript代码,帮助你快速实现这一功能。</p>
<h3>HTML代码 (index.html)html<!DOCTYPE html><html><head> <meta charset='UTF-8'> <title>HTML动态表单示例</title> <link rel='stylesheet' type='text/css' href='styles.css'></head><body> <h1>动态表单示例</h1></h3>
<form id='form1'> <h2>表单1</h2> <table id='table1'> <tr> <th contenteditable='true'>表头1</th> <th contenteditable='true'>表头2</th> <th contenteditable='true'>表头3</th> </tr> <tr> <td contenteditable='true'>数据1</td> <td contenteditable='true'>数据2</td> <td contenteditable='true'>数据3</td> </tr> </table> <br> <button type='button' onclick='addRow('table1')'>添加数据</button> <button type='button' onclick='deleteRow('table1')'>删除数据</button> </form>
<form id='form2'> <h2>表单2</h2> <table id='table2'> <tr> <th contenteditable='true'>表头1</th> <th contenteditable='true'>表头2</th> <th contenteditable='true'>表头3</th> </tr> <tr> <td contenteditable='true'>数据1</td> <td contenteditable='true'>数据2</td> <td contenteditable='true'>数据3</td> </tr> </table> <br> <button type='button' onclick='addRow('table2')'>添加数据</button> <button type='button' onclick='deleteRow('table2')'>删除数据</button> </form>
<script src='script.js'></script></body></html>
<h3>CSS代码 (styles.css)css/* styles.css */</h3>
<p>h1 { text-align: center;}</p>
<p>h2 { margin-top: 20px;}</p>
<p>table { border-collapse: collapse; width: 100%;}</p>
<p>th, td { padding: 8px; text-align: left; border-bottom: 1px solid #ddd;}</p>
<p>button { margin-right: 10px;}</p>
<h3>JavaScript代码 (script.js)javascriptfunction addRow(tableId) { const table = document.getElementById(tableId); const row = table.insertRow(-1); const cells = table.rows[0].cells;</h3>
<p>for (let i = 0; i < cells.length; i++) { const cell = row.insertCell(i); cell.innerHTML = '新数据'; cell.setAttribute('contenteditable', 'true'); }}</p>
<p>function deleteRow(tableId) { const table = document.getElementById(tableId); if (table.rows.length > 1) { table.deleteRow(-1); }}</p>
<h3>代码说明</h3>
<ol>
<li><strong>HTML</strong>: 我们创建了两个表单 (<code>form1</code>, <code>form2</code>),每个表单包含一个表格 (<code>table1</code>, <code>table2</code>)。表格的表头和数据单元格都设置了 <code>contenteditable='true'</code>,使得用户可以直接在页面上编辑内容。2. <strong>CSS</strong>: 我们使用简单的CSS样式来美化表单和表格,使其更易于阅读。3. <strong>JavaScript</strong>: <code>addRow</code> 函数用于在指定表格的末尾添加一行,<code>deleteRow</code> 函数用于删除指定表格的最后一行数据。</li>
</ol>
<h3>如何使用</h3>
<ol>
<li>将上述代码分别保存为 <code>index.html</code>, <code>styles.css</code> 和 <code>script.js</code> 文件。2. 在浏览器中打开 <code>index.html</code> 文件,即可查看效果。</li>
</ol>
<p>现在,你拥有了两个可以自定义表头、添加和删除数据的动态表单!你可以根据需要修改代码,例如增加表单数量、修改表格列数等,以满足你的实际需求。</p>
原文地址: https://www.cveoy.top/t/topic/bKHm 著作权归作者所有。请勿转载和采集!