使用DataTable对行计数匹配列值

时间:2014-08-14 15:32:46

标签: jquery datatable jquery-datatables

我想计算特定列中的值匹配的行数。请参阅以下代码:

<script type="text/javascript" charset="utf-8">

    $(document).ready(function() {

        var refreshAlertTable = $('#alert-table').dataTable( {
            "bInfo": false,
            "sAjaxSource": 'ajax/alert_json.xml',
            "bServerSide": true,
            "bJQueryUI": true,
            "bLengthChange": false,
            "bPaginate": false,
            "bFilter": false,
            "aaSorting" : [[2, "desc"]],
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if ( aData[2] == "5" )
                {
                    $('td', nRow).css('background-color', 'Red');
console.log(aData.length);
                }
                else if ( aData[2] == "4" )
                {
                    $('td', nRow).css('background-color', 'Orange');
console.log(aData.length);
                }
            },
        });

        setInterval (function() {
            refreshAlertTable.fnDraw();
        }, 5000);
    } );
</script>

第一个控制台日志显示3个圆圈和5个,但该匹配的实际计数为3.第二个控制台日志显示2个圆圈和5但结果应为2.如何只检索带圆圈的值

1 个答案:

答案 0 :(得分:1)

fnRowCallback中的aData是一个包含实际行内容的数组,因此aData.length等于表中的列数

获取彩色行数可以使用两个变量并在fnRowCallback中增加它们然后显示fnDrawCallback中的行数并将值重置为零

$(document).ready(function() {
    var red=0;//number of red rows
    var orange=0;//number of orange rows
    var refreshAlertTable = $('#alert-table').dataTable( {
        "bInfo": false,
        "sAjaxSource": 'ajax/alert_json.xml',
        "bServerSide": true,
        "bJQueryUI": true,
        "bLengthChange": false,
        "bPaginate": false,
        "bFilter": false,
        "aaSorting" : [[2, "desc"]],
        "fnRowCallback": function(nRow,aData,iDisplayIndex,iDisplayIndexFull){
            if ( aData[2] == "5" )
            {
                $('td', nRow).css('background-color', 'Red');
                red++;//if the row is red increment the value
            }
            else if ( aData[2] == "4" )
            {
                $('td', nRow).css('background-color', 'Orange');
                orange++;//if the row is orange increase the value
            }
        },
        "fnDrawCallback":function(oSettings){
        //fnDrawCallback executes after all the fnrowcallbacks
             console.log("red "+red);//show the number of red rows
             console.log("orange "+orange); //show the number of orange rows
             red=0;//reset the values to 0 for the setInterval
             orange=0;
        }
    });
    setInterval (function() {
        refreshAlertTable.fnDraw();
    }, 5000);
});