DataTable學習筆記---排序細則、列隱藏[3]


        耽誤了好幾天,因為要做一個嵌入式的實驗-android內核編譯與裁剪,很久之前裝的wubi不知道為什么運行出錯了,然后看着當前的win7系統覺得有點討厭了,也是因為快1年半沒裝機了,所以就重新裝機了,結果就各種杯具,統計裝了2次win7,2次win8,2次wubi,期間碰到了不知多少問題,另一方面限於這可惡的網速,着實讓我蛋疼了一把,然后又是各種壓力,本人大三了,到了要找實習單位的時候,還有是否決定考研,也挺煩心的。今天趁着有點時間了,繼續我們的dataTable學習吧。

      1.DataTable排序

             1.1 基礎知識

               dataTable可以多列排序,在表格中,按住shirt,然后選擇需要排序的列就可以了。下面是四個重要屬性的區分:

              屬性'bSort':初始化的時候定義整個table是否排序

$(document).ready( function () {
  $('#example').dataTable( {
    "bSort": false
  } );
} );

              屬性'bSortable':初始化的時候定義具體哪一列是否可排序

$(document).ready( function() {
  $('#example').dataTable( {
    "aoColumns": [ 
      { "bSortable": false },
      null,
      null,
      null,
      null
    ] } );
} );

            屬性'aaSorting':初始化表格的時候,選擇以怎樣的規則排序

// Sort by 3rd column first, and then 4th column
$(document).ready( function() {
  $('#example').dataTable( {
    "aaSorting": [[2,'asc'], [3,'desc']]
  } );
} );

            屬性'asSorting':設置具體哪一行的排序規則

// Using aoColumns
$(document).ready( function() {
  $('#example').dataTable( {
    "aoColumns": [
      null,
      { "asSorting": [ "asc" ] },
      { "asSorting": [ "desc", "asc", "asc" ] },
      { "asSorting": [ "desc" ] },
      null
    ]
  } );
} );

                 通過上面的介紹基本上應該清楚這四個屬性的含義與不同了吧。接下來給介紹簡單排序

             1.2 簡單排序,單列排序

                  table初始化的時候使用屬性'aaSorting',屬性值是一個array。

$(document).ready(function() {
    $('#example').dataTable( {
        "aaSorting": [[ 4, "desc" ]]
    } );
} );

             1.3 多列排序

                 有了上面的單例排序,外加基礎知識里的aaSorting的介紹,范例上面就有,這里就不寫了。

             1.4 特殊排序規則

                 這里需要分清幾個要點:

                 1. 首先是sSortDataType.定義數據源類型的排序(主要是input類型),dom-text,dom-select,dom-checkbox。突然發現以前有個做傻了,當初用checkbox的時候,就應該直接設置sSortDataType.

                 2.屬性sType:定義這列數據類型,包括(string,numeric,date,html)。

                 3.不帶類型檢測的排序

                    老實說這個挺復雜的,怎么寫排序規則,然后怎么實現,盡管dataTable有范例,但是沒怎么看懂,下面我給出我改過的范例,如果有錯誤,如果大家發現好一點的范例,歡迎跟我分享,如果有時間我能理解它的范例,我也會及時更新這篇博文的。

function initTable(){
    tableTest = $('#tableTest').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "aaData": [
      ['101', 'aaa', '91,1', '2012-10-10', 'X'],
      ['102', 'bbb', '92,5', '2012-3-19', 'X'],
      ['103', 'ccc', '89,5', '2013-3-21', 'X'],
      ['105', 'eee', '95', '2011-11-11', 'C'],
      ['104', 'ddd', '91', '2013-2-22', 'X']
    ],
        'aaSorting':[ [1,'asc'],[2,'asc'] ],
        'aoColumns':[
        {'sTitle':'ID', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Name', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Score', 'sType': 'numeric-comma','sWidth':'20%','sClass':'center'},
        {'sTitle':'Date', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'downLoad', 'sWidth':'20%','sClass':'center',
            "mRender": function ( data, type, full ) {
                return '<a href="'+data+'">Download</a>';
              }}
          ]
    });
}

jQuery.fn.dataTableExt.oSort['numeric-comma-asc']  = function(a,b) {
    var x = (a == "-") ? 0 : a.replace(",", "." );
    var y = (b == "-") ? 0 : b.replace( ",", "." );
    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};
 
jQuery.fn.dataTableExt.oSort['numeric-comma-desc'] = function(a,b) {
    var x = (a == "-") ? 0 : a.replace(",", "." );
    var y = (b == "-") ? 0 : b.replace( ",", "." );
    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

      定義排序規則的時候肯定會定義兩個,其實應該是三個,當>,<,=..一般定義的排序類型有數字,帶小數的,string。

      下面是當表格中是一些input-type不是text類型的排序。那么首先應該先獲取例如type=checkbox的值對吧

/* Create an array with the values of all the checkboxes in a column */
$.fn.dataTableExt.afnSortData['dom-checkbox'] = function  ( oSettings, iColumn )
{
    var aData = [];
    $( 'td:eq('+iColumn+') input', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( this.checked==true ? "1" : "0" );
    } );
    return aData;
}

      2.DataTable列隱藏

var tableTest;
function initTable(){
    tableTest = $('#tableTest').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "aaData": [
      ['101', 'aaa', '91,1', '2012-10-10', 'X'],
      ['102', 'bbb', '92,5', '2012-3-19', 'X'],
      ['103', 'ccc', '89,5', '2013-3-21', 'X'],
      ['105', 'eee', '95', '2011-11-11', 'C'],
      ['104', 'ddd', '91', '2013-2-22', 'X']
    ],
        'aaSorting':[ [1,'asc'],[2,'asc'] ],
        'aoColumns':[
        {'sTitle':'ID', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Name', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Score','sWidth':'20%','sClass':'center'},
        {'sTitle':'Date', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'downLoad', 'sWidth':'20%',"bVisible": false,"bSearchable": false, 'sClass':'center',
            "mRender": function ( data, type, full ) {
                return '<input type="text" class="userName" value="'+data+'"/>';
              }}
          ]
    });
    
    $('#tableTest').find('.userName').each(function(){
        console.log($(this).val());
    });
}

       有兩個bVisible和bSearchable,如果設置bVisible:false,那么這列數據是不可訪問的,bSearchAble:false是可以訪問的,我感覺這邊做的不是很好哎,就比方說我們一般都喜歡對表添加一列隱藏列,里面記錄每行的id,方便數據訪問,但是貌似這招這樣不行。我想能不能用mReader來做,就比方上面代碼,設置type='hidden',試驗發現不行,看來我是明顯天真了。但是想到mReader:function(data,type,full)其中的full就是這一列的所有信息,試驗了一下,的卻訪問隱藏的那一列,那么通過這種變相的方法就可以訪問隱藏的數據了。

      總結一下,可以通過mReader:function(data,type,full)中的full參數獲取一行所有信息(包括隱藏列),獲取到的是一列字符串,然后通過spilt轉換位數組,然后選取第幾個。

//代碼不全,就是那么個意思
{'sTitle':'ID', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Name', 'sWidth':'20%','sClass':'center'},
        {'sTitle':'Score','sWidth':'20%','sClass':'center'},
        {'sTitle':'Date', 'sWidth':'20%','bVisible':false,'sClass':'center'},
        {'sTitle':'downLoad', 'sWidth':'20%',"bSearchable": false, 'sClass':'center',
            "mRender": function ( data, type, full ) {
                return '<input type="text" class="userName" value="'+full+'"/>';
              }}
          ]
    });
    var s;
    var data;
    $('#tableTest').find('.userName').each(function(){
        var data = $(this).val();
        var s = data.split(",");
        console.log(s[3]);
    });
//輸出
//2012-10-10 
//2012-3-19 
2013-3-21
2013-2-22 
2011-11-11

   通過點擊按鈕確定該列是否可見或是隱藏---自帶了范例

  通過oTable.fnSetColumnVis(iCol,1/0);前一個參數是第幾列。下面的代碼應該挺好看懂的吧。

$(document).ready(function() {
    $('#example').dataTable( {
        "sScrollY": "200px",
        "bPaginate": false
    } );
} );
 
function fnShowHide( iCol )
{
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#example').dataTable();
     
    var bVis = oTable.fnSettings().aoColumns[iCol].bVisible;
    oTable.fnSetColumnVis( iCol, bVis ? false : true );
}

   通過點擊按鈕確定是否顯示該列詳細信息---自帶范例

  

/* Formating function for row details */
function fnFormatDetails ( oTable, nTr )
{
    var aData = oTable.fnGetData( nTr );
    var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
    sOut += '<tr><td>Rendering engine:</td><td>'+aData[1]+' '+aData[4]+'</td></tr>';
    sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
    sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
    sOut += '</table>';
     
    return sOut;
}
 
$(document).ready(function() {
    /*
     * Insert a 'details' column to the table
     */
    var nCloneTh = document.createElement( 'th' );
    var nCloneTd = document.createElement( 'td' );
    nCloneTd.innerHTML = '<img src="../examples_support/details_open.png">';
    nCloneTd.className = "center";
     
    $('#example thead tr').each( function () {
        this.insertBefore( nCloneTh, this.childNodes[0] );
    } );
     
    $('#example tbody tr').each( function () {
        this.insertBefore(  nCloneTd.cloneNode( true ), this.childNodes[0] );
    } );
     
    /*
     * Initialse DataTables, with no sorting on the 'details' column
     */
    var oTable = $('#example').dataTable( {
        "aoColumnDefs": [
            { "bSortable": false, "aTargets": [ 0 ] }
        ],
        "aaSorting": [[1, 'asc']]
    });
     
    /* Add event listener for opening and closing details
     * Note that the indicator for showing which row is open is not controlled by DataTables,
     * rather it is done here
     */
    $('#example tbody td img').live('click', function () {
        var nTr = $(this).parents('tr')[0];
        if ( oTable.fnIsOpen(nTr) )
        {
            /* This row is already open - close it */
            this.src = "../examples_support/details_open.png";
            oTable.fnClose( nTr );
        }
        else
        {
            /* Open this row */
            this.src = "../examples_support/details_close.png";
            oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
        }
    } );
} );

效果截圖:

 

       好了,寫了也好幾個小時了,一邊學一邊寫,有關於DataTable這個控件大家應該有一些了解了,基本的操作都應該會了吧,現在主要涉及到表格數據,這個涉及到json,老實說我還不太會呢,准備找個時間學一下json數據格式,然后順便講講dataTable從后台獲取數據以及填充;還有增加一行,刪除一行,復雜表頭,修改表頭,挺簡單的吧,有時間的話就寫一下,或者以后項目中用到的話,到時候總結吧。

       如果大家在使用DataTable這個控件的時候遇到了問題,也可以給我留言,我盡量幫大家解決,當然我不保證我肯定會,大家一起學習。

       Keep on fighting!!

       以上全部都屬個人原創,請大家轉載的時候附上原創鏈接: http://www.cnblogs.com/tonylp


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM