DataTables搭配Tabledit报TypeError: Cannot set properties of undefined (setting 'nTf')求助
解决DataTables + Tabledit 报错 "TypeError: Cannot set properties of undefined (setting 'nTf')"
问题场景
使用DataTables异步加载数据,配合Tabledit实现表格编辑功能时触发上述错误;注释editable配置项后报错消失,但该配置是指定可编辑列的必需项。
错误原因
Tabledit初始化时机过早:XMLHttpRequest是异步请求,在请求返回并完成DataTables数据渲染前,Tabledit就已执行初始化,此时表格tbody中无实际数据行,Tabledit无法找到目标元素,导致设置nTf时触发undefined错误。
解决方法
将Tabledit的初始化代码移到DataTables初始化完成的回调内部,确保表格数据完全渲染后再初始化编辑功能。
修正后的完整代码
<html> <head> <title>Person Information</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" /> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script> <script> $(document).ready(function () { var baseurl = "https://run.mocky.io/v3/391adcbb-160c-4111-b853-2e273700676b"; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", baseurl, true); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var persons = JSON.parse(xmlhttp.responseText); $.fn.dataTable.ext.errMode = 'none'; $("#example").DataTable({ data: persons, "columns": [{ "data": "id" }, { "data": "username" }, { "data": "email" }, { "data": "avatar" } ] }); // 移至此处,确保表格已渲染数据 $('#example').Tabledit({ url: 'action.php', dataType: 'json', eventType: 'dblclick', editButton: false, columns: { identifier: [0, 'id'], editable: [ [1, 'username'], [2, 'email'] ] } }); } }; xmlhttp.send(); }); </script> </head> <body> <div class="container"></div> <div class="container"> <table id="example" style="width:100%"> <thead> <tr> <th>id</th> <th>username</th> <th>email</th> <th>avatar</th> </tr> </thead> <tfoot> <tr> <th>id</th> <th>username</th> <th>email</th> <th>avatar</th> </tr> </tfoot> </table> </div> </body> </html>
内容的提问来源于stack exchange,提问作者Mohit H
相关产品推荐
相关产品推荐

