原生 JS 实现品牌列表:添加、删除与动态行号功能全解析
以下是一个使用原生 JavaScript 和 ECMAScript 高级语法实现的品牌列表的示例代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>品牌列表</title> </head> <body> <h1>品牌列表</h1> <input type="text" id="brandNameInput" placeholder="输入品牌名称"> <button onclick="addBrand()">添加</button> <table border="1" id="brandTable"> <thead> <tr> <th>行号</th> <th>品牌名称</th> <th>状态</th> <th>创建时间</th> <th>操作</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>品牌 1</td> <td>已启用</td> <td>2023-09-10 10:00:00</td> <td><button onclick="deleteBrand(this)">删除</button></td> </tr> <tr> <td>2</td> <td>品牌 2</td> <td>已禁用</td> <td>2023-09-11 11:00:00</td> <td><button disabled>删除</button></td> </tr> </tbody> </table> <script> // 定义一个全局变量来存储行号 let rowNumber = 2; function addBrand() { const brandName = document.getElementById('brandNameInput').value; if (brandName) { const table = document.getElementById('brandTable').getElementsByTagName('tbody')[0]; const newRow = table.insertRow(); const cell1 = newRow.insertCell(0); const cell2 = newRow.insertCell(1); const cell3 = newRow.insertCell(2); const cell4 = newRow.insertCell(3); const cell5 = newRow.insertCell(4); cell1.innerHTML = ++rowNumber; cell2.innerHTML = brandName; cell3.innerHTML = '已启用'; cell4.innerHTML = new Date().toISOString(); cell5.innerHTML = `<button onclick="deleteBrand(this)">删除</button>`; } } function deleteBrand(button) { const row = button.parentNode.parentNode; if (row.cells[2].innerHTML === '已启用') { if (confirm('确定要删除这一行吗?')) { row.parentNode.removeChild(row); updateRowNumbers(); } } else { alert('只有已启用的品牌才能删除!'); } } function updateRowNumbers() { const rows = document.getElementById('brandTable').getElementsByTagName('tbody')[0].rows; for (let i = 0; i < rows.length; i++) { rows[i].cells[0].innerHTML = i + 1; } rowNumber = rows.length; } </script> </body> </html> ``` 在上述代码中,实现了添加品牌、删除品牌(已启用状态)以及动态更新行号的功能。时间使用了原生的`new Date()`来获取当前时间。 ######[AI写代码神器 | 849点数解答 | 2024-11-18 21:15:31]
- Python 实现简易密码设置系统:多种功能交互与安全要点揭秘(字节豆包 | 286点数解答 | 2025-03-28 10:43:21)356
- C语言实现多功能密码设置系统:含代码及安全注意要点(字节豆包 | 414点数解答 | 2025-03-28 10:43:55)344
- C 语言实现:超简单密码设置系统,含代码与注意要点!(字节豆包 | 519点数解答 | 2025-03-28 12:42:02)385
- C语言实现密码管理系统:含功能代码与安全注意事项(字节豆包 | 409点数解答 | 2025-04-05 18:09:56)333
- C语言实现多功能密码系统:初始化、确认、设置、显示、重置与退出(字节豆包 | 454点数解答 | 2025-04-05 18:48:42)333
- C语言实现密码管理系统:含初始化、确认、设置、显示、重置及退出功能(字节豆包 | 413点数解答 | 2025-04-06 15:37:16)279
- C 语言实现密码管理系统:含初始化、确认、设置、显示、重置及退出功能(字节豆包 | 403点数解答 | 2025-04-06 15:37:54)294
- jQuery 实现动态操作 DOM:打造可增删任务的待办事项列表应用(百度文心 | 1015点数解答 | 2024-10-26 23:41:22)432
- jQuery 打造实用待办事项列表:输入添加、点击删除一步到位!(阿里通义 | 1139点数解答 | 2024-10-29 08:44:48)351
- jQuery 实现动态操作 DOM:打造带添加与删除功能的待办事项列表应用(阿里通义 | 687点数解答 | 2024-10-29 09:25:06)358
- jQuery 实战:打造可添加与删除任务的待办事项列表应用(字节豆包 | 499点数解答 | 2024-10-29 20:40:48)275
- Java 实战:汽车类继承车辆基类,实现属性扩展与方法重写(字节豆包 | 220点数解答 | 2025-04-15 14:38:26)299