在DataTable中,如何按部分值对列进行排序? [英] In DataTable, how to sort a column by partial value?
问题描述
我正在使用DataTables(jQuery的Table插件)作为我的Web设计工具.但是我遇到了一个问题,因为我想按部分值对列进行排序.
例如,有一个名为"Speaker"的列,其值为"Lin教授","Dr.Yu","Chen教授"等.对列进行排序时,顺序为:
1.于博士"
2.陈教授"
3.林教授".
我想按他们的名字而不是首字母排序,这意味着按以下顺序排序:
1.陈教授"
2.林教授"
3.于博士".
另一个示例是列平均值(5%偏差)",其值为"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按部分值对列进行排序?
I am using DataTables, a Table plug-in for jQuery, as a tool on my web design. But I encounter a problem since I would like to sort a column by partial value.
For example, there is a column named "Speaker", with values "Prof. Lin", "Dr. Yu", "Prof. Chen", and so on. When sorting the column, the order will be:
1."Dr. Yu"
2."Prof. Chen"
3."Prof. Lin".
I would like to sort by their first name rather than the first letter, which means ordering as:
1."Prof. Chen"
2."Prof. Lin"
3."Dr. Yu".
Another example is a column "Average(5% bias)" with values "78.0 (-2.5~2.5)", "90.5 (-1.5~1.5)", "130.0 (-3.0~3.0)", and so on. When sorting the column, the order will be:
1."130.0 (-3.0~3.0)"
2."78.0 (-2.5~2.5)"
3."90.5 (-1.5~1.5)".
I would like to sort by their average value rather than the first letter (DataTable thinks the column values are string rather than float), which means ordering as:
1."78.0 (-2.5~2.5)"
2."90.5 (-1.5~1.5)"
3."130.0 (-3.0~3.0)".
In my database, there are two columns to store the data, like "title" and "forst_name", "average" and "bias". So it is easy to separate as two parts in a <td></td>
tag.
Is it possible to sort a column by partial value using DataTables?
推荐答案
我已经完成了示例代码用于Title
排序.您可以对Average
列进行其余操作.
I have done a sample code for the Title
sort. You may do the rest for the Average
column.
<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" }
]});
});
感谢这篇文章
这篇关于在DataTable中,如何按部分值对列进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!