最近项目中用了Bootstrap的样式风格,控件用了JQuery Datatables,主要有几下几点目标:
- 实现BootStrap风格的table,使用Ajax获取数据,并有勾选项
- 可以实现全选,单击勾选
- 双击行弹出编辑对话框,点击保存使用Ajax传送到服务端保存
- 实现批量删除
- 分页操作(下次再记录)
- 查询操作(下次再记录)
- 排序操作(下次再记录)
第一部分:
编写一个只有thead的table,tbody会在JS函数中自动生成。
HMTL代码如下:
1 <table id="example" class="table table-striped table-bordered table-hover"> 2 <thead> 3 <tr> 4 <th class="center"> 5 <label class="position-relative"> 6 <input type="checkbox" class="ace"/> 7 <span class="lbl"></span> 8 </label> 9 </th> 10 <th>公司名称</th> 11 <th>简称</th> 12 <th>所在城市</th> 13 <th>地址</th> 14 <th>联系人</th> 15 <th>联系电话</th> 16 </tr> 17 </thead> 18 19 </table>
直接在该Table上加入JS代码
1 $('#example').dataTable({ 2 "oLanguage": { //语言设置 3 "sProcessing": "正在加载中......", 4 "sLengthMenu": "每页显示 _MENU_ 条记录", 5 "sZeroRecords": "对不起,查询不到相关数据!", 6 "sEmptyTable": "表中无数据存在!", 7 "sInfo": "当前显示 _START_ 到 _END_ 条,共 _TOTAL_ 条记录", 8 "sInfoFiltered": "数据表中共为 _MAX_ 条记录", 9 "sSearch": "搜索", 10 "oPaginate": { 11 "sFirst": "首页", 12 "sPrevious": "上一页", 13 "sNext": "下一页", 14 "sLast": "末页" 15 } 16 }, 17 bAutoWidth: false, //自动适应宽度 18 "bFilter": false, //查询 19 "bSort": true, //排序 20 "bInfo": false, //页脚信息 21 "bLengthChange": false, //改变每页显示数据数量 22 "bServerSide": true, //服务器数据 23 "sAjaxSource": '/XXX/XXX/GetList', 24 "bProcessing": true, //当datatable获取数据时候是否显示正在处理提示信息。 25 "bPaginate": true, //显示分页器 26 "iDisplayLength ": 10, //一页显示条数 27 "aoColumns": [ 28 { 29 //自定义列 30 "sName":"Id", //Ajax提交时的列明(此处不太明白,为什么用两个属性--sName,mDataProp) 31 "mDataProp": "Id", //获取数据列名 32 "sClass": "center", //样式 33 "bStorable": false, //该列不排序 34 "render": function(data, type, row) { //列渲染 35 return '<label class="position-relative">' + 36 '<input type="checkbox" class="ace" value="'+data+'"/>' + 37 '<span class="lbl"></span>' + 38 '</label>'; 39 } 40 }, 41 { 42 "sName": "Name", 43 "mDataProp": "Name", 44 "bSearchable": true, //检索可用 45 "bStorable": true 46 }, 47 { 48 "sName": "CustomerSN", 49 "mDataProp": "CustomerSN", 50 "bSearchable": false, 51 "bStorable": false 52 }, 53 { 54 "mDataProp": "City", 55 "sName": "City" 56 }, 57 { 58 "sName": "Address", 59 "mDataProp": "Address" 60 }, 61 { 62 "sName": "Contact", 63 "mDataProp": "Contact" 64 }, 65 { 66 "sName": "ContactPhone", 67 "mDataProp": "ContactPhone" 68 } 69 ] 70 });
第二部分:
加入全选,点击一行将Checkbox勾选功能,使用纯JS实现
1 $(document).on('click', 'th input:checkbox', function() { 2 var that = this; 3 $(this).closest('table').find('tr > td:first-child input:checkbox') 4 .each(function() { 5 this.checked = that.checked; 6 $(this).closest('tr').toggleClass('selected'); 7 }); 8 }); 9 10 //对行单击添加监听事件 11 $('#example tbody').on('click', 'tr', function () { 12 var tr = $(this).closest('tr'); 13 var checkbox = tr.find('td:first-child input:checkbox')[0]; 14 checkbox.checked = !checkbox.checked; 15 16 });