扩展Shaun 的好答案,至少有两种方法可以测试dd-MMM-yyyy 格式的填充程序的需要。在与JSLint进行激烈协商后,我修改了 Shaun 的代码(我发誓它讨厌我写的每一行 ECMA)。
使用 IE 条件
如果您已经在使用 IE 条件 ( <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
),那么您可以测试HTML.lt-ie9
并有条件地定义新的排序算法,然后调用 dataTables:
//test for html.lt-ie9
if ($('html.lt-ie9').length) {
//create the new magic sorting
var customDateDDMMMYYYYToOrd = function (date) {
"use strict"; //let's avoid tom-foolery in this function
// Convert to a number YYYYMMDD which we can use to order
var dateParts = date.split(/-/);
return (dateParts[2] * 10000) + ($.inArray(dateParts[1].toUpperCase(), ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]) * 100) + dateParts[0];
};
// This will help DataTables magic detect the "dd-MMM-yyyy" format; Unshift so that it's the first data type (so it takes priority over existing)
jQuery.fn.dataTableExt.aTypes.unshift(
function (sData) {
"use strict"; //let's avoid tom-foolery in this function
if (/^([0-2]?\d|3[0-1])-(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)-\d{4}/i.test(sData)) {
return 'custom-date-dd-mmm-yyyy';
}
return null;
}
);
// define the sorts
jQuery.fn.dataTableExt.oSort['custom-date-dd-mmm-yyyy-asc'] = function (a, b) {
"use strict"; //let's avoid tom-foolery in this function
var ordA = customDateDDMMMYYYYToOrd(a),
ordB = customDateDDMMMYYYYToOrd(b);
return (ordA < ordB) ? -1 : ((ordA > ordB) ? 1 : 0);
};
jQuery.fn.dataTableExt.oSort['custom-date-dd-mmm-yyyy-desc'] = function (a, b) {
"use strict"; //let's avoid tom-foolery in this function
var ordA = customDateDDMMMYYYYToOrd(a),
ordB = customDateDDMMMYYYYToOrd(b);
return (ordA < ordB) ? 1 : ((ordA > ordB) ? -1 : 0);
};
};
//now call the dataTable plugin against the target tables (in this case, any table with `class="dataTable"`)
$('table.datatable').dataTable();
请参阅http://jsfiddle.net/jhfrench/nEsCt/ 上的 IE 条件示例
使用Modernizr进行测试
另一方面,如果您倾向于使用 Modernizr 来测试功能,我们可以定义 Modernizr 测试,然后使用 Modernizr 执行测试并有条件地加载 shim 魔法(来自 .js 文件),然后调用 dataTables :
//define the Modernizr test
Modernizr.addTest('valid_date_dd_mmm_yyyy', function() {
return !isNaN(Date.parse("17-MAY-2013"));
});
//if Modernizr determines "dd-mmm-yyyy" dates are not supported, load the following JavaScript resources
Modernizr.load([
{
test: Modernizr.valid_date_dd_mmm_yyyy,
nope: 'http://appliedinter.net/Workstream/common_files/js/dataTable_shim_dd-MMM-yyyy.js',
complete: function () {
$(document).ready(function () {
//now call the dataTable plugin against the target tables (in this case, any table with `class="dataTable"`)
$('table.datatable').dataTable();
});
}
}
]);
请参阅http://jsfiddle.net/jhfrench/tNkGC/ 上的 Modernizr 方法