jquery表格展开关闭
封面图
•
2025-10-28
•
jQuery
228
0
0
0
在 jQuery 中实现表格的**展开/关闭**功能,通常是指对表格中的某一行(如子行)进行动态显示或隐藏。这种功能常用于展示嵌套数据(例如:主表记录和子记录),比如购物车中每个订单下的商品详情。 下面是一个简单的 **jQuery 表格展开/关闭** 示例,使用 HTML + CSS + jQuery 实现: --- ## ✅ 示例:表格展开/关闭 ### 1. HTML 结构 ```html <table id="myTable" border="1"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>操作</th> </tr> </thead> <tbody> <tr class="parent"> <td>张三</td> <td>25</td> <td><button class="toggle">展开</button></td> </tr> <tr class="child" style="display: none;"> <td colspan="3">这是张三的详细信息</td> </tr> <tr class="parent"> <td>李四</td> <td>30</td> <td><button class="toggle">展开</button></td> </tr> <tr class="child" style="display: none;"> <td colspan="3">这是李四的详细信息</td> </tr> </tbody> </table> ``` --- ### 2. jQuery 脚本 ```html <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function () { $('.toggle').click(function () { // 找到下一个兄弟元素(即子行) var $nextRow = $(this).closest('tr').next('.child'); if ($nextRow.is(':visible')) { $nextRow.hide(); $(this).text('展开'); } else { $nextRow.show(); $(this).text('关闭'); } }); }); </script> ``` --- ### 3. 效果说明 - 每个“父行”(`.parent`)有一个按钮,点击后会切换下一行(`.child`)的显示状态。 - 初始时,子行是隐藏的(`style="display: none;"`)。 - 点击“展开”按钮后,子行显示;再次点击“关闭”,子行隐藏。 --- ## 🔄 可选增强功能 你可以进一步扩展这个功能,例如: ### - 使用动画效果 ```javascript $nextRow.slideToggle(); ``` ### - 支持多个层级的子行 可以为子行添加 `.child` 类,并递归查找下级。 ### - 图标切换(如箭头方向) 用图标代替文字,通过 CSS 或图标库(如 Font Awesome)来表示“展开/关闭”。 --- ## ✅ 总结 | 功能 | 实现方式 | |------|----------| | 展开/关闭 | jQuery 的 `show()` / `hide()` 或 `slideToggle()` | | 选择目标行 | 使用 `next()`、`find()`、`closest()` 等方法 | | 切换按钮文字 | 通过 `text()` 修改按钮内容 | --- 如果你有更复杂的需求(如从服务器加载数据、多级嵌套等),也可以告诉我,我可以帮你扩展代码。
上一篇:
jquery--点击后滑动展开或关闭DIV层
下一篇:
内嵌iframe的jquery拖动层
标题录入,一次不能超过6条
留言
评论