[英]How do I sort hyperlinks in a DataTable numerically?
我有以下超链接网格视图列,需要按IncidentId进行数字排序。 有没有一种方法可以将数据保留为超链接,并且仅按IncidentId排序? 当我使用以下javascript函数对其进行“数字”排序时,它将中断并且该列将不进行排序。 如果我将sType声明为“ string”或“ html”进行排序,但是它按字母顺序而不是数字排序数据,换句话说,它将以93、82、71、40、123、122、121而不是123、122、121、93、82、71、40。
<asp:HyperLinkField HeaderText="Incident ID:" DataNavigateUrlFields="IncidentId"
DataNavigateUrlFormatString="view.aspx?id={0}" DataTextField="IncidentId"/>
<script type="text/javascript">
$(function () {
$('#GridViewIncidents').dataTable({
"bFilter": false,
"bSort": true,
"aoColumnDefs": [{ "sType": "numerical", "aTargets": [0]}]
});
});
</script>
我的解决方案是先定义一个addType
扩展点:
jQuery.extend(jQuery.fn.dataTableExt, {
addType: function (options) {
var optionsSpecified = options != null && options.name && options.detect && options.compare;
if (!optionsSpecified) {
alert('addColumnType: options are not specified correctly.');
} else {
this.aTypes.unshift(function (sData) {
return options.detect(sData) ? options.name : null;
});
this.oSort[options.name + '-asc'] = function (x, y) {
return options.compare(x, y);
};
this.oSort[options.name + '-desc'] = function (x, y) {
return options.compare(x, y) * -1;
};
}
}
});
此后,我们使用上述扩展点定义用于识别整数链接的扩展:
(function () {
var linkRegex = new RegExp("^<a.*>([0-9]+)</a>$");
function parseIntLink(sData) {
var result = linkRegex.exec(sData);
return result == null ? NaN : parseInt(result[1], 10);
}
jQuery.fn.dataTableExt.addType({
name: 'int-link',
detect: function (sData) {
return !isNaN(parseIntLink(sData));
},
compare: function (x, y) {
return parseIntLink(x) - parseIntLink(y);
}
});
})();
请参阅此博客以获取更多详细信息。 (免责声明:这是我的博客)。
您需要覆盖数据表排序功能的默认比较器。
jQuery.fn.dataTableExt.aTypes.unshift(
function (sData) {
if (sData !== null && sData.match('^<.*[0-9]+</.*>$')) {
return 'intComparer';
}
return null;
}
);
上面的代码将找到包裹在html标记中的所有整数,并告诉Datatables使用自定义比较器函数。
然后,我们需要为此定义比较功能:
jQuery.fn.dataTableExt.oSort['intComparer-asc'] = function (a, b) {
var value1 = parseInt(getInnerHTML(a));
var value2 = parseInt(getInnerHTML(b));
return ((value1 < value2) ? -1 : ((value1 > value2) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['intComparer-desc'] = function (a, b) {
var value1 = parseInt(getInnerHTML(a));
var value2 = parseInt(getInnerHTML(b));
return ((value1 < value2) ? 1 : ((value1 > value2) ? -1 : 0));
};
这会剥离标签并按数值排序。
只需在设置表之前将所有这些代码放在script标记中,它就可以工作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.