嗨,
我正在处理数据表,并注意到使用自定义排序函数时 Chrome 上有一个非常奇怪的行为。
这是我的发现:
- 在处理小型列表(少于 10 个)时,自定义排序在 Chrome 和 Firefox 中运行良好
- 当处理稍大的表格(仍然很小,大约 30 个条目)时,Firefox 仍然会返回有效的排序结果,但 Chrome 无法做到这一点。
我做了一个 fiddle ,你可以在其中看到这种行为。在里面你会看到两个相同的表,只是数据大小不同,第一个表很小 - 无论是 Chrome 还是 Firefox,一切都可以正常工作。
第二个更大,chrome 无法对其进行排序。
fiddle : https://jsfiddle.net/ogoossens/d35cb4eh/3/
我的部分代码
自定义排序函数:
jQuery.fn.dataTableExt.oSort["customSort-desc"] = function (x, y) {
return formatPrice(x) < formatPrice(y);
};
jQuery.fn.dataTableExt.oSort["customSort-asc"] = function (x, y) {
return formatPrice(x) > formatPrice(y);
};
如何清理数字格式
function formatPrice(unformattedPrice) {
// For debugging purposes
let returnValue = unformattedPrice;
// Here I check if there is "-" if so teh price shall be considered as 0
if (unformattedPrice == "-") {
returnValue = 0;
} else {
// If not lets get rid of EVERYTHING except the numbers
returnValue = returnValue.replace(" ","");
returnValue = returnValue.replace("$","");
}
// Lets make sure itll be considered float
returnValue = parseFloat(returnValue);
return returnValue;
}
我如何定义我的表格:
$('#example-ok').DataTable({
"paging": false,
"searching": false,
"info": false,
order: [],
"columns": [
{
"bSortable": true,
"sType": "customSort"
},
]
});
尝试在 Firefox 和 Chrome 中打开完整的 Fiddle,并告诉我是否只有我在第二个表无法排序的情况下。
谢谢
最佳答案
问题是要排序的数组具有相同的值,当您具有相同的值时,您应该使用类似以下内容的内容:
jQuery.fn.dataTableExt.oSort["customSort-desc"] = function (x, y) {
if(formatPrice(x) == formatPrice(y)){
return 0;
}
if(formatPrice(x) < formatPrice(y)){
return 1
}
if(formatPrice(x) > formatPrice(y)){
return -1
}
};
完整示例在这里:https://jsfiddle.net/15qdx4g9/1/
使用 .sort()
的行为相同。说实话,我不知道为什么 Chrome 和 Firefox 会有这样的区别,我猜是因为 .sort()
关于javascript - DataTables - 使用 CHROME 时排序结果无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51911127/