Based on JQuery grid plugin can drag the list DataTables stepped pit remember

Foreword

Recent projects capable of dragging the column in order to adjust the position of the table columns plug --- DataTables, which is currently the only I found there is such a plug-in function.

We found that not many available cases, and most of them use words unknown in the lookup process. This article describes the overall process of using this plug.

If there is not dragging the column to adjust the column position of the order of demand, it is recommended not to use this plug-in, large pit. Later I will have time to write a named use Bootstrap-table form plug-in , to use much stronger than this plugin

text

English officer Networks: Https://Datatables.Net/

Chinese official website: http://www.datatables.club/

Recommendations lot of reference to the English official website reference (reference) https://datatables.net/reference/index documentation and Chinese official website of http://www.datatables.club/reference

Try not to Chinese official website to download when downloading files, download the form because of less need of additional plug-ins, the English official website Download: https://datatables.net/download/index

Download mode is selected, Bootstrap, JQuery, DataTables, as well as the following plug-in ColReorder (This plug-in is required to drag the column), but in this proposal, how to download party of choice

Server pagination

Note that this article only describes the way paging server, because the client page is very simple, write the necessary parameters when you create the table, then the data into the form is completed

DataTables is based on JQuery and Bootstrap, so before using this plugin need to introduce these two libraries (framework) documents required

After the introduction of other places to download and JQuery Bootstrap and in DataTables official website to download the file

html code is as follows:

<table class="table table-striped display table-bordered" style="margin: 0;" cellspacing="0" width="100%" id="table"></table>

 

js code as follows:

Server configuration code:

Stepped pit: special attention to the interaction ajax here must be written in the form of configuration items, if written elsewhere incoming data, the number of pages displayed when the number of pages after the second page of the point is always the second page, and the first one can not click

Copy the code
= 0 judgeTable the let; 
function Table () { 
  IF (_this.judgeTable) {// This is in order not to destroy the initialization table, otherwise an error 
    $ ( '# table') DataTable () destroy ();.. // destruction table 
  } 
  _this.judgeTable =. 1; 
  $ ( '# table') the DataTable ({. 
    colReorder: to true, // start column drag 
    scrollX: true, // scroll bar about 
    ordering: false, // Sort 
    searching: false, // participating in the search 
    lengthMenu: [10, 25, 50 , 100], // set the page size to select the item 
    pageLength: _this.pageSize, // set page size 
    displayStart: _this.pageNum - 1, // set the current form in the first few pages, starting from 0 
    serverSide: true, // the server is turned tab 
    order: [[1, 'asc ']], // asc ascending, descending desc  
    ajax: function (data, callback, settings) {
      // data parameters, a single page of records data.length number; data.start record number is started; (data.start / data.length) +1 is the current page number 
    $ .ajax ({
              url:. _this $ ajaxConfig.url + "Role / Page pageNum =?" + _this.pageNum + "& pageSize =" + _this.pageSize, 
              of the type: "GET", 
              contentType: "the Application / json", 
              Cache: false, 
              xhrFields : { 
                withCredentials: to true 
              }, 
              Success: function (result) { 
                IF (result.code == 0) { 
                  the let the dataTable = []; 
                  // modify row data field to identify that the form which the result is to put you the data table, the acquired field data if you and your columns provided in the same configuration, this step is omitted 
                      ID: item.id, 
                      name: item.name, for, 
                  result.data.list.forEach (function (item, index) {
                    dataTable.push ({ 
    },
                      the remark: item.remark, 
                      enableEdit: item.enableEdit 
                    }) 
                  }) 
                  // modify the setting data field to identify that the form 
                  var = {returndata 
                    recordsTotal: result.data.total, 
                    recordsFiltered: result.data.total, 
                    Data: the dataTable 
                  } ; 
                  the callback (returndata); 
                } 
              }, 
              error: function (error) { 
                the console.log (error); 
              } 
            }); 
    columns: [// column provided 
      { 
        Data: null, 
        checkboxes: {// This is the box 
          SelectRow: to true 
        } 
      }, 
      { 
        title: "User name", 
        Data: "the userName", 
      }, 
      { 
        title: "description" , 
        Data: "the remark" 
      }, 
      { 
        title: "edit user status", 
        Data: null, 
        render: function (Data, type, row, Meta) {// set render the cell contents of this column, there are provided I button 
          // row json target line data is required when turned json string element into 
          the let the JSON.stringify, rowData = (row); 
          the let className = ''; 
          the let elementText = '';
          if(row.flag) {
            = className 'csbtn-Yes'; 
            elementText = 'enabled'; 
          } the else { 
            className = 'csbtn-NO'; 
            elementText = 'disabled'; 
          } 
        // It should be noted in particular, can not be used to transmit data rowData double quotes, or single quotes, or without quotes 
          return "<span class = 'csbtn" + className + "' Data-Table =" +, rowData + ">" + elementText + "</ span>"; 
        } 
      } 
    ], 
    "Language" : { 
      "lengthMenu": "_MENU_ of data per page", 
      "emptyTable": "no data", 
      "info": "Show total _TOTAL_ _START_ to _END_ article", 
      "infoEmpty ":" Show Total 0 0 0 ", 
      " infoFiltered ":" (filtered from _MAX_ bar) ", 
      " the Thousands ":", ", 
      "loadingRecords": "Loading ...", 
      "Processing": "Loading ...", 
      "Search": "search:", 
      "zeroRecords": "data not found", 
      "the SELECT": { 
        "rows": "" 
      }, 
      "the paginate": { 
        " first ":" first page ", 
        " last ":" last page ", 
        " Next ":" Next ", 
        " Previous ":" Previous " 
      } 
    } 
  }); 
}
Copy the code

 

Table of related events:

Stepped pit: Events do not write code and create a table within a function, or the number of times after a single trigger event trigger will increase clicks, such as: the first trigger once, it will automatically trigger twice after the second click

Change the page size of the event:

$ ( '# Table') ON ( 'length.dt', function (E, Settings, len) {. 
     the pageSize = len; // change the variable memory page size, len is the page size of the changed 
});

 

Feed Event:

$ ( '# Table') ON ( 'page.dt', function () {. 
       pageNum = $ ( '# Table') the DataTable () Page () +. 1;.. // change the current number of pages stored in the variable, $ ( '# table') DataTable () page () method to get to the current page number is 0 from the beginning. 
 });

 

Initialization event:

$('#table').on('init.dt',function(e,settings,len) {
        console.log(e,settings,len)
});

 

Select the line effect event:

Stepped pit 1: When you add a click event, you must first use the off () remove the event, otherwise it does not refresh the page premise trigger again to re-render the table after the first click can lead to multiple triggering events

Step on pit 2: used when setting properties checked here is the JQuery prop method, the pit must not be used to set the properties attr (after use when clicked on again after setting this property check box is invalid), because JQuery version 1.6 after the introduction of a prop method, designed to obtain form properties

Copy the code
$ (Document) .off ( 'the Click', '# Role Table tbody-TR'); 
$ (Document) .on ( 'the Click', '# Role Table tbody-TR', function () { 
          // for each row the class name is provided, and the operation box 
          IF ($ (the this) .hasClass ( 'Selected')) { 
            $ (the this) .removeClass ( 'Selected'); 
            $ (the this) .find ( 'TD> INPUT'). prop ( "the checked", to false); 
          } {the else 
            IF (! $ (the this) .hasClass ( 'estimateRole')) { 
              $ (the this) .addClass ( 'Selected'); 
              $ (the this) .find ( 'TD> . the INPUT ') First () prop ( "the checked", to true);. 
            } 
          } 
}); 
// click the check box is not selected row, so it needs to set the event checkbox 
$ (document) .on ( 'change', '#role-table tbody tr td input', function () { 
          if ($ (this) .parent (). parent (). hasClass ( 'selected')) {
            $(this).parent().parent().removeClass('selected');
            $(this).parent().parent().find('td>input').prop("checked",false)
          } else {
            $(this).parent().parent().addClass('selected');
            $(this).parent().parent().find('td>input').first().prop("checked",true)
          }
});
$('#table').DataTable().rows('.selected').data();//获取选中的行(带有相应类名的行)
Copy the code

 

Multilayer header:

When using a multilayer header, you need to replace the column configuration columnFefs

Copy the code
columnDefs: [
            {
              "targets":[0],//第一列
              "orderable": false,
              "render": function (data, type, row, meta) {
                var text = "<input class='single-check-input'  type='checkbox'>";
                return text;
              }
            },
            {
              "targets":["json"],//最后一列
              "render": function (data, type, row, meta) {
                console.log(data)
                var text = "";
                text = "<a href=# onclick=showCollisonJsonData(this)>查看详情</a>"
                return text;
              }
            },
]
Copy the code

 

Configuration header functions:

Copy the code
function configComplexHeader(headerInfo) {
        let _this = this;
        var theader = $('#detail-table-header');
        var headrFirstRow = $('<tr></tr>');
        var childHeaders = [];
        headerInfo.forEach(function (singleHeader) {
          var headerName = singleHeader.name;
          var colspanNum = singleHeader.childList.length;
          var thE = $('<th></th>',
            {
              colspan: colspanNum,
              text: headerName,
              style: "text-align:center"
            }
          );
          headrFirstRow.append(thE);
          (singleHeader.childList).forEach(function (childObj) {
            var childHeadTitle = childObj.name;
            if (childHeadTitle === "json_data") {
              childHeadTitle = "操作";
            }
            childHeaders.push(childHeadTitle);
          });
        });
        var tmpThE = $('<th/>',{
          colspan: 1,
        });
        headrFirstRow.prepend(tmpThE);

        var headerSecondRow = $('<tr></tr>');
        childHeaders.forEach(function (childHeader) {
          var className = "normal";
          if (childHeader === "操作") {
            className = "json";
          }
          headerSecondRow.append($('<th/>',{text:childHeader,class: className}));
        });

        var tmpSecThE = $('<th></th>',{
          class: "check-all-input-th",
          html: "<input type='checkbox' class='check-all-input'>"
        });
        headerSecondRow.prepend(tmpSecThE);
        theader.append(headrFirstRow);
        theader.append(headerSecondRow);
 }
//表头数据
var headerInfo = [{"name":"碰撞字段","childList":[{"field":"col_c_cardno_3_0","name":"身份证号/身份证号"}]},
          {"name":"火车票数据","childList":[{"field":"c_mobile_1_0","name":"电话"},{"field":"c_email_2_0","name":"E-mail地址"},{"field":"a_name_1_0","name":"姓名"},{"field":"a_time_2_0","name":"订票时间"},{"field":"a_time_3_0","name":"出发时间"},{"field":"json_data_0","name":"json_data"}]},
          {"name":"户政人口","childList":[{"field":"a_name_1_1","name":"姓名"},{"field":"a_sex_2_1","name":"性别"},{"field":"a_address_3_1","name":"地址"},{"field":"a_marriage_4_1","name":"婚姻状况"},{"field":"a_edu_level_5_1","name":"文化程度"},{"field":"a_company_6_1","name":"单位"},{"field":"a_address_7_1","name":"籍贯"},{"field":"a_nation_8_1","name":"民族"},{"field":"json_data_1","name":"json_data"}]}]

configComplexHeader(headerInfo);
Copy the code

 

The effect is as follows:

 

Guess you like

Origin www.cnblogs.com/daofaziran/p/11882740.html