ASP.NET Core嵌套表格:jQuery点击按钮无法选中内部元素问题
解决ASP.NET Core嵌套表格的展开/折叠及图标切换问题
你的问题主要出在事件绑定的目标选择和嵌套表格内容的获取逻辑上,咱们一步步来修复:
问题核心分析
- 事件触发范围太窄:你把点击事件绑定在了
<i class="fa fa-plus">元素上,但用户实际点击的是按钮区域,很难精准点到图标,导致事件经常不触发。 - 嵌套表格路径错误:
$(this).next().html()里的this指向的是<i>元素,它根本没有同级的表格div——隐藏表格是按钮的同级元素,不是图标的。
修复后的完整实现
第一步:调整HTML(修正重复ID问题)
循环生成的元素不能用相同的id,把隐藏表格的id改成class:
@if (item.Geometrias != null) { <button type="button" class="btn-outline-warning"> <i class="fa fa-plus"></i> </button> <!-- 把id改为class,避免重复ID --> <div class="tblGeometrias" style="display:none"> <table class="table table-striped" cellpadding="0" cellspacing="0"> <!-- 嵌套表格内容不变 --> </table> </div> }
第二步:修改jQuery脚本(修正事件绑定和逻辑)
$("body").on("click", ".btn-outline-warning", function () { // 1. 获取按钮内部的图标元素 const $icon = $(this).find("i.fa"); // 2. 获取按钮同级的隐藏表格 const $nestedTable = $(this).next(".tblGeometrias"); // 3. 获取当前行的父tr const $currentTr = $(this).closest("tr"); // 判断当前是展开还是折叠状态 if ($icon.hasClass("fa-plus")) { // 生成嵌套行并插入 const $nestedRow = $("<tr class='nested-row'><td></td><td colspan='999'></td></tr>"); $nestedRow.find("td:last").html($nestedTable.html()); $currentTr.after($nestedRow); $nestedRow.hide().fadeIn(); // 切换图标为减号 $icon.removeClass("fa-plus").addClass("fa-minus"); } else { // 删除已展开的嵌套行 $currentTr.next(".nested-row").remove(); // 切换图标为加号 $icon.removeClass("fa-minus").addClass("fa-plus"); } });
改动说明
- 把事件绑定到按钮本身,用户点击按钮任意区域都能触发,彻底解决图标选不中的问题
- 通过
$(this).find("i.fa")精准定位按钮内部的图标,轻松切换class - 用
$(this).next(".tblGeometrias")正确获取到同级的隐藏表格内容 - 增加了折叠逻辑,让按钮支持切换展开/折叠状态,更符合常规交互预期
这样修改后,你的嵌套表格展开/折叠和图标切换功能就能正常工作了。
内容的提问来源于stack exchange,提问作者Jackal
相关产品推荐
相关产品推荐

