且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 jQuery DataTable 的所有页面中选择所有复选框

更新时间:2023-11-20 23:06:16

试试这个代码:

$(document).ready(function () { 
    var oTable = $('#example').dataTable({
        stateSave: true
    });

    var allPages = oTable.fnGetNodes();

    $('body').on('click', '#selectAll', function () {
        if ($(this).hasClass('allChecked')) {
            $('input[type="checkbox"]', allPages).prop('checked', false);
        } else {
            $('input[type="checkbox"]', allPages).prop('checked', true);
        }
        $(this).toggleClass('allChecked');
    })
});

魔法应该发生在fnGetNodes():

fnGetNodes():获取表体中使用的TR节点数组

fnGetNodes(): Get an array of the TR nodes that are used in the table's body

编辑

这个替代解决方案主要用于调试(看看它是否有效).几乎不是最优的代码:

This alternative solution is mostly for debugging (to see if it works). Hardly optimal code:

$(document).ready(function () { 
    var oTable = $('#example').dataTable({
        stateSave: true
    });

    var allPages = oTable.cells( ).nodes( );

    $('#selectAll').click(function () {
        if ($(this).hasClass('allChecked')) {
            $(allPages).find('input[type="checkbox"]').prop('checked', false);
        } else {
            $(allPages).find('input[type="checkbox"]').prop('checked', true);
        }
        $(this).toggleClass('allChecked');
    })
});