如何为Ajax DataTables每行的title字段添加onclick跳转事件
问题
我用JSON数据填充DataTables表格,原本每行的title字段通过a标签携带schoolId跳转至详情页,现在希望替换为onclick事件,通过调用window.open()打开目标页面,需要为每行的title字段数据绑定该事件,暂未找到可行方案,寻求技术帮助。
表格结构
<table class="datatables-basic table table-bordered"> <thead> <tr> <th></th> <th></th> <th></th> <th>schoolName</th> <th>HeadName</th> <th>PhoneNumber</th> <th>HeadPhoneNumber</th> <th>Address</th> <th>IsActive</th> <th>DO</th> </tr> </thead> </table>
原DataTable脚本片段
$(function () { var dt_basic_table = $('.datatables-basic'), dt_basic; if (dt_basic_table.length) { var listFilesUrl = "https://localhost:44309/AllSchools"; dt_basic = dt_basic_table.DataTable({ ajax: listFilesUrl, columns: [ { data: '' }, { data: 'schoolId' }, { data: 'schoolId' }, // 要修改的title列 { data: 'title', render: function (data, type, row) { return $('<a>') .attr({ target: "_blank", href:"https://localhost:44309/RenderSchool?schoolId=" + row.schoolId }) .text(data) .wrap('<div></div>') .parent() .html(); } }, { data: null, render: function (data, type, row){ var details = row.headFirstName + " " + row.headLastName; return details; } }, { data: 'phoneNumber' }, { data: 'headPhoneNumber' }, { data: 'address' }, { data: 'isActive' }, { data: '' } ], // 其他配置项... }); } });
解决方案
提供两种可行方案,按需选择:
方案1:直接在render函数中生成带onclick的元素
修改title列的render函数,直接生成绑定了onclick事件的元素,替代原来的a标签:
{ data: 'title', render: function (data, type, row) { // 用span模拟链接样式,绑定onclick事件 return `<span style="cursor:pointer;color:#0d6efd;text-decoration:underline;" onclick="window.open('https://localhost:44309/RenderSchool?schoolId=${row.schoolId}', '_blank')">${data}</span>`; } }
如果偏好使用a标签(去掉href避免默认跳转),也可以这样写:
{ data: 'title', render: function (data, type, row) { return `<a href="javascript:void(0);" onclick="window.open('https://localhost:44309/RenderSchool?schoolId=${row.schoolId}', '_blank')">${data}</a>`; } }
方案2:使用事件委托(推荐)
由于DataTables是动态渲染数据,事件委托更高效且避免重复绑定问题,步骤如下:
- 修改title列的render函数,仅渲染带自定义属性的元素:
{ data: 'title', render: function (data, type, row) { // 添加自定义属性存储schoolId,同时模拟链接样式 return `<span class="school-title" data-schoolid="${row.schoolId}" style="cursor:pointer;color:#0d6efd;text-decoration:underline;">${data}</span>`; } }
- 在DataTables初始化完成后,添加事件委托代码:
// 监听表格内school-title类元素的点击事件 $('.datatables-basic').on('click', '.school-title', function() { const schoolId = $(this).data('schoolid'); window.open(`https://localhost:44309/RenderSchool?schoolId=${schoolId}`, '_blank'); });
方案优势
- 仅绑定一次事件,性能更优
- 表格动态刷新数据后,事件依然有效
- 分离渲染逻辑和事件逻辑,代码更易维护
内容的提问来源于stack exchange,提问作者Pezhvak
相关产品推荐
相关产品推荐

