JQuery 数据表中的自定义排序功能,如 "anti-the"

Custom Sorting Function In JQuery Datatable like "anti-the"

我想为 Jquery 数据表创建自定义排序函数,例如

anti-the

我有一个专栏,其中包含学生的全名以及他们的敬语,例如。 Mr. Fname Mname Lname.

排序时应该忽略第一个 Mr.|Mrs.|Ms.并应根据 Fname

中的剩余数据排序

我试过了,但没用

jQuery.extend(jQuery.fn.dataTableExt.oSort, {
  "anti-the-pre": function(a) {
    return a.replace(/^mrs\.|^mr\.|^ms\. /i, "");
  },
  "anti-the-asc": function(a, b) {
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
  },
  "anti-the-desc": function(a, b) {
    return ((a < b) ? 1 : ((a > b) ? -1 : 0));
  }
});

$.ajax({
  url: '/DataService.asmx/getData',
  method: 'post',
  dataType: 'json',
  success: function(data) {
    var t = $('#studentDataTable').DataTable({
        data: data,
        "columnDefs": [{
          type: 'anti-the',
          targets: 0
        }],
      }
    });
});

Here is the Jsfiddle Example. Anyone knows how to do this ?

问题是替换后有前导空白。你最终排序 ' Hardik Vinod Thaker' 而不是 'Hardik Vinod Thaker' 所以

return a.replace(/^mrs\.|^mr\.|^ms\. /i, "").trim();

正则表达式专家可能会将空格包含为单词边界 \b。但是您没有义务使用自定义排序,您可以在您已经在使用的 render 函数中完成所有操作:

render: function(data,type,row) {
   var concatName = data['fname']+' '+data['mname']+' '+data['lname']
   return type == 'sort' 
      ? concatName.replace(/^mrs\.|^mr\.|^ms\. /i, "").trim()
      : concatName
}

当 dataTables 需要对列的值进行排序时,则传递不带敬语的串联名称。演示 -> https://jsfiddle.net/hn8v9hqx/