我有以下代码。而且我想知道为什么它只能以一种方式起作用而不能以另一种方式起作用。
<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Chart</title>
<link href="./css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="./js/jquery-3.1.0.min.js"></script>
<script src="./js/jquery.dataTables.min.js"></script>
<script>
/*
// THIS BLOCK DOES NOT WORK
var tbldata;
$(document).ready
(
function()
{
tbldata = $("#tbldata").DataTable();
}
);
*/
// THIS SINGLE LINE WORKS
var tbldata = $("#tbldata").DataTable();
</script>
</head>
<body>
<div>
<table id="tbldata">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
如果取消注释标记为无效的代码块并注释掉有效的代码行,则会出现以下错误。
jQuery.Deferred exception: Cannot read property 'aDataSort' of undefined TypeError: Cannot read property 'aDataSort' of undefined
at V (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:65:443)
at va (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:70:61)
at HTMLTableElement.<anonymous> (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:91:148)
at Function.each (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:2815)
at r.each (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:1003)
at r.m [as dataTable] (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:82:388)
at r.h.fn.DataTable (http://192.168.33.10:5000/static/js/jquery.dataTables.min.js:166:245)
at HTMLDocument.<anonymous> (http://192.168.33.10:5000/static/test.html:30:45)
at j (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:29568)
at k (http://192.168.33.10:5000/static/js/jquery-3.1.0.min.js:2:29882) undefined
在不带任何选项的情况下调用DataTables初始化程序时,它需要填充,thead
以便它可以尝试检测列及其属性。
将至少一个<th>
元素添加到您的thead,然后注释的代码将起作用。
未注释行没有真正的工作。在运行javascript时,页面上尚不存在该元素!因此,选择器将获取0个元素,并且初始化程序并未真正运行,因此没有错误。
另外(也是我首选的初始化DT的方法)...为初始化程序提供一个列定义数组。
$('#mytable').DataTable({
columns: [{ title: 'First Name', data: 'FirstName' }] //etc, etc...
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句