我的场景:
我正在尝试对使用DataTable
jquery插件的表的日期列进行排序,我已经对表进行了排序,但文本字段有空格。因此,当我按"ASC"顺序排序时,空文本字段将首先占据。这种情况不应该发生。我想对表格进行排序,不包括空的文本框。
我尝试了以下代码:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"customdatesort-pre": function (formElement) {
// returns the "weight" of a cell value
var r, x;
var a = $(formElement).val();
if (a === null || a === "") {
// for empty cells: weight is a "special" value which needs special handling
r = false;
} else {
// otherwise: weight is the "time value" of the date
x = a.split("/");
r = +new Date(+x[2], +x[1] - 1, +x[0]);
}
//console.log("[PRECALC] " + a + " becomes " + r);
return r;
},
"customdatesort-asc": function (a, b) {
// return values are explained in Array.prototype.sort documentation
if (a === false && b === false) {
// if both are empty cells then order does not matter
return 0;
} else if (a === false) {
// if a is an empty cell then consider a greater than b
return 1;
} else if (b === false) {
// if b is an empty cell then consider a less than b
return -1;
} else {
// common sense
return a - b;
}
},
"customdatesort-desc": function (a, b) {
if (a === false && b === false) {
return 0;
} else if (a === false) {
return 1;
} else if (b === false) {
return -1;
} else {
return b - a;
}
}
});
我发现此代码存在问题:
在上面的代码中,您可以看到"customdatesort-pre": function (formElement)
。参数formElement
只接受空值,而不接受带有某些日期值的文本框。
我需要什么:
我需要对日期列进行排序,不包括空的文本框。
使用自定义排序pre
废弃asc
和desc
。如果已经定义了pre
,则永远不会调用asc
和desc
方法。pre
是一种优化功能,每个单元调用一次,然后内部分类器将使用该结果进行排序。请参阅datatables.net.上的此线程
相反,您可以将pre
函数代码放在自定义排序文字之外,并从asc
和desc
方法中调用它:
customdatesortPre = function (formElement) {
//customdatesort-pre code
}
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
"customdatesort-asc": function (a, b) {
a = customdatesortPre(a), b = customdatesortPre(b);
...
},
"customdatesort-desc": function (a, b) {
a = customdatesortPre(a), b = customdatesortPre(b);
...
}
});
演示->http://jsfiddle.net/9j9gpsrn/