在DataTable中,如何按部分值对列进行排序?
In DataTable, how to sort a column by partial value?
我正在使用 DataTables,一个用于 jQuery 的 Table 插件,作为我的网页设计工具。但是我遇到了一个问题,因为我想按部分值对列进行排序。
例如,有一个名为 "Speaker" 的列,其值为 "Prof. Lin"、"Dr. Yu"、"Prof. Chen" 等。对列进行排序时,顺序为:
1."Dr. Yu"
2."Prof. Chen"
3."Prof. Lin"。
我想按他们的名字而不是第一个字母排序,这意味着排序为:
1."Prof. Chen"
2."Prof. Lin"
3."Dr. Yu".
另一个例子是 "Average(5% bias)" 列的值为“78.0 (-2.5~2.5)”、“90.5 (-1.5~1.5)”、“130.0 (-3.0~3.0)”,等等。对列进行排序时,顺序为:
1."130.0 (-3.0~3.0)"
2."78.0 (-2.5~2.5)"
3.“90.5(-1.5~1.5)”。
我想按它们的平均值而不是第一个字母排序(DataTable 认为列值是字符串而不是浮点数),这意味着排序为:
1."78.0 (-2.5~2.5)"
2."90.5 (-1.5~1.5)"
3."130.0 (-3.0~3.0)".
在我的数据库中,有两列存储数据,如 "title" 和 "forst_name"、"average" 和 "bias"。因此很容易将 <td></td>
标签中的两个部分分开。
是否可以使用 DataTables 按部分值对列进行排序?
我已经完成 sample code Title
排序。您可以完成 Average
列的其余部分。
标记
<table id="report">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dr. Yu</td>
</tr>
<tr>
<td>Prof. Chen</td>
</tr>
<tr>
<td>Prof. Lin</td>
</tr>
</tbody>
</table>
JavaScript/jQuery
$(document).ready(function () {
function getValue(titleValue) {
return titleValue.replace(/^Prof\.\s+|^Dr\.\s+/g, '');
}
jQuery.fn.dataTableExt.oSort['title-asc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['title-desc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
$('#report').dataTable({"aoColumns": [
{ "sType": "title" }
]});
});
感谢this post
我正在使用 DataTables,一个用于 jQuery 的 Table 插件,作为我的网页设计工具。但是我遇到了一个问题,因为我想按部分值对列进行排序。
例如,有一个名为 "Speaker" 的列,其值为 "Prof. Lin"、"Dr. Yu"、"Prof. Chen" 等。对列进行排序时,顺序为:
1."Dr. Yu"
2."Prof. Chen"
3."Prof. Lin"。
我想按他们的名字而不是第一个字母排序,这意味着排序为:
1."Prof. Chen"
2."Prof. Lin"
3."Dr. Yu".
另一个例子是 "Average(5% bias)" 列的值为“78.0 (-2.5~2.5)”、“90.5 (-1.5~1.5)”、“130.0 (-3.0~3.0)”,等等。对列进行排序时,顺序为:
1."130.0 (-3.0~3.0)"
2."78.0 (-2.5~2.5)"
3.“90.5(-1.5~1.5)”。
我想按它们的平均值而不是第一个字母排序(DataTable 认为列值是字符串而不是浮点数),这意味着排序为:
1."78.0 (-2.5~2.5)"
2."90.5 (-1.5~1.5)"
3."130.0 (-3.0~3.0)".
在我的数据库中,有两列存储数据,如 "title" 和 "forst_name"、"average" 和 "bias"。因此很容易将 <td></td>
标签中的两个部分分开。
是否可以使用 DataTables 按部分值对列进行排序?
我已经完成 sample code Title
排序。您可以完成 Average
列的其余部分。
标记
<table id="report">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dr. Yu</td>
</tr>
<tr>
<td>Prof. Chen</td>
</tr>
<tr>
<td>Prof. Lin</td>
</tr>
</tbody>
</table>
JavaScript/jQuery
$(document).ready(function () {
function getValue(titleValue) {
return titleValue.replace(/^Prof\.\s+|^Dr\.\s+/g, '');
}
jQuery.fn.dataTableExt.oSort['title-asc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['title-desc'] = function (a, b) {
var x = getValue(a);
var y = getValue(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
$('#report').dataTable({"aoColumns": [
{ "sType": "title" }
]});
});
感谢this post