2017-06-13 102 views
0

我使用tablesorter(https://mottie.github.io/tablesorter/docs/index.html) 排序我的HTML表格。在tablesorter中自定義排序順序 - jquery

我有一個排序我找不到howtoo。即。

  • (4)
  • (DNS)
  • DNS

要被分類爲:

  • (4)
  • (DNS)
  • DNS

簡言之:()將被忽略,並且數字排序,首先數字然後按字母順序。

我已經看過如何替換字符,(因爲某些排名不工作,因此爲「空」) 我見過的解析器要求我創建每個標題和已知值以替換。 即:

$.tablesorter.addParser({ 
    id: 'nummeriek', 
    is: function(s) { 
     return false; 
    }, 
    format: function(s) { 
     // format your data for normalization 
     return s.toLowerCase().replace('dns',999).replace('(dns)',999).replace('(4)',4); 
    }, 
    type: 'numeric' 
}); 

$('.tablesorter').tablesorter({ 
     headers: { 
      6: { 
       sorter:'nummeriek' 
      } 
     } 
}); 

如果我必須爲每一個可能的表的內容我最終創造數百替換()語句的做到這一點。因爲我的分數從1到100因此(1)到(100)也是可能的...

必須有一個更簡單的方法。任何幫助深表感謝。

回答

0

默認的digit解析器「假定」包含在圓括號中的數字是負數;這是在會計中指示負數的常用方法(ref)。

要解決這個問題,你就需要稍微修改(demo

$(function() { 
    $.tablesorter.addParser({ 
    id: 'nummeriek', 
    is: function(s) { 
     return false; 
    }, 
    format: function(str) { 
     // format your data for normalization 
     var s = str.replace(/[()]/g, ""), 
     n = parseFloat(s); 
     return !isNaN(n) && isFinite(n) ? n : s; 
    }, 
    type: 'numeric' 
    }); 

    $('.tablesorter').tablesorter({ 
    headers: { 
     0: { 
     sorter: 'nummeriek' 
     } 
    } 
    }); 
}); 

註解析器:該解析器總是返回沒有括號,例如一個非數字的字符串「(dns)」將變成「dns」。我保持這種方式,所以「(dns)」條目將排序,就好像它們是「dns」一樣。

+0

現在,這真棒。謝謝! – Pieter

+0

我剩下的一件事就是涉及的標題數量。由於這是一列表,我可以很容易地有一個2,8,12列的可變數量。我嘗試了我在這裏找到的addClass方法:https://stackoverflow.com/questions/9014962/jquery-tablesorter-custom-parser-to-all-headers,但我無法得到它適用於所有專欄..我是否缺少什麼? – Pieter

+0

哎呀,對不起,我錯過了你的問題。在'headers'選項中,您可以使用jQuery選擇器來定位列而不是從零開始的索引 - 'headers:{'.nummeriek':{sorter:'nummeriek'}}'([example](https://mottie。github.io/tablesorter/docs/example-options-headers.html))。或者,向需要它的每一列添加一個「sorter-nummeriek」類。 – Mottie