ASP.NET后台生成表格:点击单元格无法获取数据问题排查
问题:ASP.NET后台生成表格点击单元格无法获取数据
我在后台代码中创建ASP.NET表格,为部分单元格添加onclick属性触发模态弹窗,希望将触发点击的单元格内的数据提取并显示到弹窗的标签中。表格可正常生成,点击事件能触发弹窗,但无法获取单元格内的数据。
后台代码
Table1.Rows(i).Cells(y).Text = "For" & "<br />" & info(x).RoomFor.Trim & "<br />" & "Tel" & "<br />" & info(x).RoomPhone.Trim Table1.Rows(i).Cells(y).Attributes.Add("onclick", "ShowSuccess();") Table1.Rows(i).Cells(y).Attributes.CssStyle.Add("cursor", "pointer")
ASPX页面代码
function ShowSuccess() { var tr = $(this).closest('tr').find("td:eq(0)").text(); alert(tr); $('#Text1').val('Wombat'); // testing purposes $('#Lbl1').text('Wombat'); // testing purposes $("#mySuccess").modal("show"); }
问题原因
核心问题是**this指向错误**:直接通过onclick="ShowSuccess()"调用函数时,函数内部的this并没有指向触发点击的单元格元素,而是指向全局对象(浏览器环境下为window),导致无法通过$(this)定位到目标单元格及对应行的数据。
解决方案
方法一:传递当前元素作为参数
- 修改后台事件绑定代码,将当前单元格元素传入函数:
Table1.Rows(i).Cells(y).Attributes.Add("onclick", "ShowSuccess(this);")
- 更新前端JS函数,接收参数并使用:
function ShowSuccess(element) { // 获取点击单元格所在行的第一个td内容 var rowFirstCellText = $(element).closest('tr').find("td:eq(0)").text(); alert(rowFirstCellText); // 获取当前点击单元格的内容 var currentCellText = $(element).text(); // 将数据赋值到弹窗控件 $('#Text1').val(currentCellText); $('#Lbl1').text(currentCellText); $("#mySuccess").modal("show"); }
方法二:使用事件委托(推荐)
这种方式避免了直接在元素上绑定事件的耦合问题,更符合前端最佳实践:
- 后台移除onclick属性绑定,添加统一类名方便选择:
// 移除原onclick绑定行 // Table1.Rows(i).Cells(y).Attributes.Add("onclick", "ShowSuccess();") Table1.Rows(i).Cells(y).Attributes.CssStyle.Add("cursor", "pointer") // 添加类名 Table1.Rows(i).Cells(y).CssClass = "clickable-cell"
- 前端通过事件委托绑定点击事件:
$(document).on('click', '.clickable-cell', function() { var rowFirstCellText = $(this).closest('tr').find("td:eq(0)").text(); alert(rowFirstCellText); var currentCellText = $(this).text(); $('#Text1').val(currentCellText); $('#Lbl1').text(currentCellText); $("#mySuccess").modal("show"); });
内容的提问来源于stack exchange,提问作者DKX4HWS
相关产品推荐
相关产品推荐

