jQuery-Datatables下拉列表仅适用于某些列

时间:2016-05-27 08:04:03

标签: javascript jquery datatables

使用此代码和我见过的所有示例,我可以向所有列添加下拉菜单,如图所示:

enter image description here

var table = $('#myTable').DataTable({
        dom: 'lfBrtip',

        initComplete: function () {
        this.api().columns().every( function () {
            var column = this;
            var select = $('<select><option value=""></option></select>')
                .appendTo( $(column.header()))
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );

                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );

            column.data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' )
            } );
        } );
.......
    }

我如何仅为第2列和第3列添加下拉菜单?

2 个答案:

答案 0 :(得分:2)

您应该使用each获取要设置下拉列表的列索引。

var table = $('#myTable').DataTable({
        dom: 'lfBrtip',

        initComplete: function () {
        var api = this.api();
         this.api().columns().eq(0).each( function ( index ) {
           if(index == 1 || index == 2)
           {
            var column = this;
            var select = $('<select><option value=""></option></select>')
                .appendTo( $(api.column(index).header()))
                .on( 'change', function () {
                    var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                    );

                    column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                } );
              var i = 0;
              api.column(index).data().unique().sort().each( function ( d, j ) {
                select.append( '<option value="'+d+'">'+d+'</option>' );
              } );
           }
        } );
.......
    }

答案 1 :(得分:0)

您要做的就是添加以下两行

var table = $('#myTable').DataTable({
    dom: 'lfBrtip',

    initComplete: function () {
    this.api().columns().every( function () {
        if(this[0] == 2 || this[0] == 3){//add
        var column = this;
        var select = $('<select><option value=""></option></select>')
            .appendTo( $(column.header()))
            .on( 'change', function () {
                var val = $.fn.dataTable.util.escapeRegex(
                    $(this).val()
                );

                column
                    .search( val ? '^'+val+'$' : '', true, false )
                    .draw();
            } );

        column.data().unique().sort().each( function ( d, j ) {
            select.append( '<option value="'+d+'">'+d+'</option>' )
        } );
    } // add
    } );
    // ...
}