jQuery dataTables - 基于原始行数据的自定义过滤

时间:2015-11-02 22:34:53

标签: javascript datatables

JSBin:http://live.datatables.net/nujehixu/3/edit?js,console,output

$(document).ready( function () {

  // push our custom filter onto the stack of filters
  $.fn.dataTable.ext.search.push(function(settings, searchData, index, rowData, counter) {
    // get filter value
    var value = $("#example_filter > label > input").val().toLowerCase();
    // check filter value against original row data
    var original = rowData[1].toLowerCase();
    console.log(original);
    return original.indexOf(value) > -1;
  });

  function addEllipsis(original, charLimit) {
    if (original.length > charLimit) {
      // substring the original and add ellipsis with a title attribute of the original
      return '<div title="' + original + '">' + original.substr(0, charLimit) + '&hellip;' + '</div>';
    }
    // return the original value since it is already short enough
    return '<div title="' + original + '">' + original + '</div>';
  }

  var table = $('#example').DataTable({
    columnDefs: [
      {
        targets: 1,
        render: function (data, type, row) {
          // render with ellipsis if necessary
          return addEllipsis(data, 6);
        }
      }
    ]
  });
} );

查看链接的示例,我尝试使用基于原始行数据的自定义过滤器,但在输入过滤器值(如systems时)会出现问题。当我希望systems匹配“系统管理员”时,系统管理员的行将被过滤掉。并显示那些行。

通过source阅读,看起来首先针对搜索字符串global filter应用了compiled from the rendered values

有没有人为此找到解决方案?

2 个答案:

答案 0 :(得分:1)

您的问题是仍然执行默认搜索,并且由于列的值呈现为“system ...”,因此无法找到与“systems”的任何匹配项。你可以这样做:

$("#example_filter > label > input").unbind().bind('keyup', function() {
  var value = this.value.toLowerCase();
  // push our custom filter onto the stack of filters
  $.fn.dataTable.ext.search.push(function(settings, searchData, index, rowData, counter) {
    // get filter value
    // check filter value against original row data
    var original = rowData[1].toLowerCase();
    console.log(original);
    return original.indexOf(value) > -1; 
  });
  table.draw();
  $.fn.dataTable.ext.search.pop();
})  

更改代码 - &gt;的 http://live.datatables.net/dalesexe/4/edit

更好的答案是根据可能render()type_的{​​{1}}返回filter的不同值。在display上返回ellipied'值,否则返回原始值。您可以完全跳过自定义过滤器:

display

新代码 - &gt;的 http://live.datatables.net/dalesexe/6/edit

答案 1 :(得分:0)

问题是你的charlimit会削减字符以及与显示的数据匹配而不是原始数据。基本上找不到systems因为system是最大长度。