如何用Bootstrap Modal展示点击触发的表格隐藏用户信息
改用Bootstrap Modal弹窗展示用户详情
原代码实现了点击「View More」按钮后显示表格行内隐藏的邮箱、性别及状态信息,现在将其修改为通过Bootstrap Modal弹窗展示这些信息,具体步骤如下:
1. 引入Bootstrap依赖
使用Bootstrap Modal需要先引入Bootstrap的样式和脚本(以Bootstrap 5为例):
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
2. 添加Modal模板
在页面中插入Modal的HTML结构,用于承载用户详情:
<!-- 用户详情弹窗 --> <div class="modal fade" id="userDetailModal" tabindex="-1" aria-labelledby="userDetailModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="userDetailModalLabel">用户详情</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <label class="form-label">姓名</label> <p id="modalName"></p> </div> <div class="mb-3"> <label class="form-label">邮箱</label> <p id="modalEmail"></p> </div> <div class="mb-3"> <label class="form-label">性别</label> <p id="modalGender"></p> </div> <div class="mb-3"> <label class="form-label">状态</label> <p id="modalStatus"></p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> </div>
3. 修改JavaScript代码
优化表格渲染逻辑,移除隐藏的td元素,通过点击事件将用户数据填充到Modal并展示:
let table; // 保存全量用户数据,用于点击时快速匹配 let userList = []; const show = (data) => { userList = data; table.innerHTML = data .map(({id, name}) => `<tr> <td>${name}</td> <td> <button class="more btn btn-primary" data-id="${id}">View More</button> </td> </tr>`) .join(""); }; const load = () => { fetch("https://gorest.co.in/public/v2/users") .then(result => result.json()) .then(show); }; window.addEventListener("DOMContentLoaded", () => { table = document.getElementById('table'); // 初始化Modal实例 const userModal = new bootstrap.Modal(document.getElementById('userDetailModal')); table.addEventListener("click", (e) => { const tgt = e.target.closest("button"); if (!tgt) return; // 通过按钮的data-id匹配对应用户 const userId = parseInt(tgt.dataset.id); const user = userList.find(item => item.id === userId); if (user) { // 填充弹窗内容 document.getElementById('modalName').textContent = user.name; document.getElementById('modalEmail').textContent = user.email; document.getElementById('modalGender').textContent = user.gender; document.getElementById('modalStatus').textContent = user.status; // 展示弹窗 userModal.show(); } }); load(); });
代码说明
- 新增
userList变量存储全量用户数据,避免从DOM中读取隐藏内容,提升性能和可维护性 - 移除原代码中隐藏的td元素,简化表格结构
- 使用Bootstrap官方API创建Modal实例,通过数据填充和
show()方法完成弹窗展示 - Modal采用Bootstrap表单样式,让信息展示更规整
内容的提问来源于stack exchange,提问作者Apurav Sharma
相关产品推荐
相关产品推荐

