使用 jQuery DataTable 进行单选框选择

7
在jquery datatable中,应该选择单个复选框。
这个链接可以正常工作。
但是上面的链接使用的是 jquery.dataTables 的版本为1.10.16,而我正在使用的版本为1.9.4
是否可以在 jquery.dataTables 的版本为1.9.4 的情况下实现与上面示例中列出的相同功能呢?

为什么不自己试一下,而非在这里问呢?据我所知,是可以实现的。 - Krzysztof Janiszewski
通过将1.10.16替换为1.9.4,它无法正常工作。您能否为我提供一些链接,其中使用了jquery.datatables 1.9.4的jquery? - user752590
有人能指导我如何链接“使用jquery.dataTables 1.9.4进行单个复选框选择”吗? - user752590
不能!!选择扩展是基于1.10.x API的,你无法让它在1.9.4上工作,所使用的功能根本不受支持。 - davidkonrad
4个回答

2
在您提供的链接页面中,有许多关于使用“单选”操作的解释。
在列出的附件末尾,您可以看到所引用的.js文件。

https://cdn.datatables.net/select/1.2.5/js/dataTables.select.min.js

在您的页面中,应在 dataTable.js 之后添加此文件引用。
我认为,jquery 的版本并不重要。重要的文件是 "dataTables.select.js"!
其次,您必须更新您的 dataTable 制作代码,如下面的示例所示;
$(document).ready(function() {
    $('#example').DataTable( {
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'td:first-child' // this line is the most importan!
        },
        order: [[ 1, 'asc' ]]
    } );
} );

更新:

为什么不尝试编写自己的选择器函数呢?

例如:

$(document).ready(function() {
    $('#example').DataTable( {
            /// put your options here...
        } );

    $('#example').find("tr").click(function(){ CheckTheRow(this); });
} );

function CheckTheRow(tr){
    if($(tr).find("td:first").hasClass("selected")) return;

    // get the pagination row count
    var activePaginationSelected = $("#example_length").find("select").val();

    // show all rows
    $("#example_length").find("select").val(-1).trigger("change");

    // remove the previous selection mark
    $("#example").find("tr").each(function(i,a){
         $(a).find("td:first").removeClass("selected");
         $(a).find("td:first").html("");
     });

     // mark the picked row
     $(tr).find("td:first").addClass("selected");
     $(tr).find("td:first").html("<i class='fa fa-check'></i>");

     // re turn the pagination to first stuation
     $("#example_length").find("select")
                         .val(activePaginationSelected).trigger("change");

}

仅仅将“jquery.dataTables 1.10.16”替换为“jquery.dataTables 1.9.4”是不起作用的。它会报错“TypeError: g.ext.selector is undefined (fileName - dataTables.select.min.js 1.2.5)”,因此jquery.dataTables版本很重要。 - user752590

2

很遗憾,传统数据表不支持或没有该选择扩展功能。

解决方法:

  1. 在“mRender”回调中创建复选框元素。
  2. 将操作绑定到复选框。(这可以在fnRowCallback内部完成,也可以像下面的fiddle示例一样在外部完成)

https://jsfiddle.net/Rohith_KP/dwcatt9n/1/

 $(document).ready(function() {
  var userData = [
    ["1", "Email", "Full Name", "Member"],
    ["2", "Email", "Full Name", "Member"]
  ];

  var table = $('#example').DataTable({
    'data': userData,
    'columnDefs': [{
      'targets': 0,
      'className': 'dt-body-center',
      'mRender': function(data, type, full, meta) {
        return '<input type="checkbox" value="' + $('<div/>').text(data).html() + '">';
      }
    }],
    'order': [1, 'asc']
  });

  $('#example tr').click(function() {
    if ($(this).hasClass('row_selected'))
      $(this).removeClass('row_selected');
    else
      $(this).addClass('row_selected');
  });
});

此外,我建议您升级datatable版本。然后您就可以使用该选择扩展。


2
同样的功能是否可以在jquery.dataTables 1.9.4中实现,而不是使用jquery.dataTables 1.10.16?
可以。
但是,不能使用Select Extension,因为它需要至少版本1.10.7
对于1.9.4,可能的解决方案是:
$(document).ready(function() {
  $('#example').find("td input[type='checkbox']").click(function() {
    selectRow(this);
  });

  var table = $('#example').DataTable();

  function selectRow(clickedCheckBox) {
    var currentPage = table.fnPagingInfo().iPage;

    // Being unchecked
    if (!$(clickedCheckBox).is(':checked')) {
      $(clickedCheckBox).removeAttr('checked');
      getRow(clickedCheckBox).removeClass('selected');
      return;
    }

    var selectEntries = $("#example_length").find("select");
    var showEntriesCount = selectEntries.val();
    var totalRows = table.fnGetData().length;

    // If show entries != totalRows append total rows opiton that can be selected
    if (totalRows != showEntriesCount)
      selectEntries.append($('<option>', {
        value: totalRows,
        text: totalRows
      }));

    // Display all rows
    selectEntries.val(totalRows).trigger("change");

    // Removes all checked attribute from all the rows
    $("#example").find("td input[type='checkbox']").each(function(value, key) {
      getRow(key).removeClass('selected');
      $(key).removeAttr('checked');
    });

    // Check the clicked checkBox
    $(clickedCheckBox).prop('checked', true);
    getRow(clickedCheckBox).addClass('selected');

    // Re set the show entries count
    selectEntries.val(showEntriesCount).trigger("change");

    // If added, Remove the additional option added to Show Entries
    if (totalRows != showEntriesCount)
      selectEntries.find("[value='" + totalRows + "']").remove();

    // Go to the page on which the checkbox was clicked
    table.fnPageChange(currentPage);
  }

  function getRow(element) {
    return $(element).parent().parent();
  }
});

以上需要fnPagingInfo将用户带回初始页面。我尚未在大型数据集上测试解决方案,但已在包含150行的表格上进行了测试,应该也可以在更大的数据集上正常工作。


JSFiddle


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接