[英]How to filter jquery data table by date column?
我有一个要根据一列中的日期进行过滤的数据表。 我想根据具有一年或更早日期的lastModified列过滤数据,但是即使在某个硬编码日期对它进行过滤也是一个不错的开始。 字符串格式的数据,因此我尝试使用新的Date()函数转换为日期。
var table = $('#database').DataTable( {
fixedHeader: true,
data: dataSet,
columns: [
{ data: "processName" },
{ data: "processLob" },
{ data: "processOwner"},
{ data: "RiskReviewer"},
{ data: "lastModified"}]
} );
var filteredData = table
.column( { data: "lastModified"} )
.data()
.filter( function ( value, index ) {
return new Date(value) < 2015-10-10 ? true : false;
} );
您要做的第一件事是为日期列添加“ columnDefs”对象,并将其类型指定为“ date”。 只要您遵循一种众所周知的格式,DateTables就会内置日期解析功能。 ColumnType API定义
如果还不能完全解决问题,那么您将需要在刚创建的新columnDef对象上为数据列定义一个渲染函数。 在那里,您可以检查渲染类型,并为显示内容返回“ nice”值,并为其他所有内容返回原始数据值(最好是Date类型的值)。 渲染API定义
另外,一些一般性建议不要尝试与图书馆打架。 实际上,它非常灵活,可以处理很多事情。 因此,请尽可能使用内置的API函数。 通常,当人们尝试使用JQuery手动操作表时,事情会出错。 在幕后,DataTables插件保持大量状态,从未进入DOM。 基本上,如果API中有针对它的功能,请使用它。
编辑:即使他找到了另一个解决方案,也向原始海报问题添加了答案。
要记住的一件事是,“过滤器”仅旨在为您提供经过过滤的数据集。 它不会更改网格中的显示。 相反,您将需要在“ column()” API项上使用“搜索”来过滤DataTable中显示的行。
但是,这有一个小问题。 搜索方法仅接受常规值,不接受功能。 因此,如果要实现此功能,则可以提供一个自定义搜索功能,如下所示:
// The $.fn.dataTable.ext.search array is shared amongst all DataTables and
// all columns and search filters are evaluated in the order in which they
// appear in
// the array until a boolean value is returned.
$.fn.dataTable.ext.search.unshift(function(settings, data, dataIndex) {
// Using a negative value to get the column wraps around to the end of
// the columns so "-1" will always be your last column.
var dateColumn = $(this).column(-1);
// We get the data index of the dateColumn and compare it to the index
// for the column currently being searched.
if(dateColumn.index() !== dataIndex) {'
// Pretty sure this indicates to skip this search filter
return null;
}
var columnSearchingBy = $(this).column(dataIndex);
// Allows the data to be a string, milliseconds, UTC string format ..etc
var columnCellData = new Date(data.lastModified);
var valueToSearchBy = new Date(columnSearchingBy.search.value);
// Ok this is one of the worst named methods in all of javascript.
// Doesn't actually return a meaningful time. Instead it returns the a
// numeric value for the number of milliseconds since ~ 1970 I think.
//
// Kind of like "ticks()" does in other languages except ticks are
// measured differently. The search filter I am applying here is to
// only show dates in the DataTable that have a lastModified after or
// equal the column search.
return (valueToSearchBy.getTime() >= columnCellData.getTime());
});
// So this should use our fancy new search function applied to our datetime
// column. This will filter the displayed values in the DataTable and from
// that just a small filter on the table to get all the data for the rows
// that satisfy the search filter.
var filteredData = table
.column({ data: "lastModified"})
.search('2015-10-10')
.draw();
即使您找到了进行此操作的另一种方法,也许上述内容也会在以后为您提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.