datatable初始化demo
阿新 • • 發佈:2018-10-28
lin integer chan function search ipaddress log del wid
TypeScript代碼:
let tabledata = data as any[]; if (this.dataTable) { this.dataTable.clear(); this.dataTable.destroy(); } /* * ip = models.IPAddressField() access_time = models.DateTimeField() method = models.CharField() url = models.CharField() protocol = models.CharField() status_code = models.SmallIntegerField() size = models.BigIntegerField() referer = models.CharField() client = models.CharField() detail = models.CharField()*/ let search:boolean|object; if (this.searchParams.keyword && this.searchParams.keyword.length>0){ search = {"search": this.searchParams.keyword}; }else { search = {}; } this.dataTable = $(‘#eventstable‘).DataTable({‘data‘ : tabledata, ‘paging‘ : true, ‘lengthChange‘: true, ‘searching‘ : true, ‘ordering‘ : true, ‘info‘ : false, ‘autoWidth‘ : false, ‘columns‘: [ { title: "access_time", ‘data‘: "access_time" }, { title:"detail", ‘data‘: "detail" } ] });
事件註冊代碼,ES6的:
let table = $(‘#dataTable‘).DataTable( { data: data, ‘paging‘ : true, ‘lengthChange‘: true, ‘searching‘ : true, ‘ordering‘ : true, ‘info‘ : false, ‘autoWidth‘ : true, //使用對象數組,一定要配置columns,告訴 DataTables 每列對應的屬性 //data 這裏是固定不變的,name,position,salary,office 為你數據裏對應的屬性 columns: [ { data: ‘id‘,title:"ID" }, { data: ‘name‘,title:"名稱" }, { data: ‘id‘,title:"操作" ,"render":function (data, type, row, meta ) { return‘<button type="button" data-id="‘+data+‘" class="btn btn-primary btn-sm">執行</button>‘; }} ] } ); $("button.btn-sm").on("click",function (event) { console.log($(event.target).attr("data-id")) return false }) table.on("draw",function () { console.log("draw------>") $("button.btn-sm").on("click",function (event) { console.log($(event.target).attr("data-id")) return false }) })
解釋一下,為什麽這麽寫,初始化完需要註冊一次,每次頁面page或者排序draw完需要再註冊一次,比較奇怪的事第一次init以後的draw不會引發draw事件,所以不得不為第一次初始化完成綁定了一次。
datatable初始化demo