Juery解決tablesorter中文排序和字元範圍的方法

來源:互聯網
上載者:User

Juery解決tablesorter中文排序和字元範圍的方法

   這篇文章主要介紹了Juery解決tablesorter中文排序和字元範圍的方法,執行個體分析了jQuery針對tablesorter中文排序和字元範圍的解決方案,需要的朋友可以參考下

  tablesorter是jQuery外掛程式中比較優秀的一款表格排序外掛程式,我相信大家都使用過或有所耳聞,我在這裡就不過多介紹了,詳細資料可以看看官方網站:http://tablesorter.com/docs/(其中的demo做得比較完整)。

  在使用了tablesorter開發的幾個項目中,發現了兩種類型的排序存在問題,如下:

  第一個問題是無法對中文字元進行排序,這是因為在對字元排序時,是使用的unicode值進行的字元大小比較,代碼如下:

  Js代碼

  ?

1

2

3

4

5

6

7

8

9

10

11

12

function sortText(a,b) {

return ((a < b) ? -1 : ((a > b) ? 1 : 0));

};

function sortTextDesc(a,b) {

return ((b < a) ? -1 : ((b > a) ? 1 : 0));

};

function sortText(a,b) {

return ((a < b) ? -1 : ((a > b) ? 1 : 0));

};

function sortTextDesc(a,b) {

return ((b < a) ? -1 : ((b > a) ? 1 : 0));

};

  而我們想要得到的結果是按漢字拼音進行順序進行排序,因此我們將代碼修改為以下代碼即可:

  Js代碼

  ?

1

2

3

4

5

6

7

8

9

10

11

12

function sortText(a,b) {

return a.localeCompare(b);

};

function sortTextDesc(a,b) {

return b.localeCompare(a);

};

function sortText(a,b) {

return a.localeCompare(b);

};

function sortTextDesc(a,b) {

return b.localeCompare(a);

};

  localeCompare方法是JS內建的方法,不用多說,望文生義就知道這個方法是根據目前範圍下對字元的大小進行比較,不過這個方法無法處理多音字。

  第二個問題是無法對超出了範圍的數值型資料進行排序,這是因為在進行數實值型別轉換時,存在資料值失真的情況,例如:

  Js代碼

  ?

1

2

3

4

5

6

7

8

9

10

alert(parseFloat('9999999999999999')); // 10000000000000000

alert(parseFloat('10000000000000001')); // 10000000000000000

alert(parseFloat('10000000000000004')); // 10000000000000004

alert(parseFloat('10000000000000005')); // 10000000000000004

alert(parseFloat('10000000000000006')); // 10000000000000006

alert(parseFloat('9999999999999999')); // 10000000000000000

alert(parseFloat('10000000000000001')); // 10000000000000000

alert(parseFloat('10000000000000004')); // 10000000000000004

alert(parseFloat('10000000000000005')); // 10000000000000004

alert(parseFloat('10000000000000006')); // 10000000000000006

  這樣的偏差會使得排序結果不準確,為了避免這種問題,應該不使用原始值進行比較,而是應該引入權值,數值從左至右,每一位元值對應的權值遞減,然後根據權值和原始值計算出的新值用於比較,這就只需要修改formatFloat方法就能解決這個問題了。

  Js代碼

  ?

1

2

3

4

5

this.formatFloat = function(s) {

// TODO

var i = parseFloat(s);

return (isNaN(i)) ? 0 : i;

};

  希望本文所述對大家的jQuery程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.