2014-03-25 19 views
0

我有一個項目列表,其中有字母&數字兩種類型的值。 我需要排序他們像字母排序然後數字排序。對於如:蘋果汽車23 45 我能夠使用對它們進行排序:Jquery,字母數字值的排序和分組

$(function() { 
    $.fn.sortList = function() { 
     debugger; 
    var mylist = $(this); 
    var listitems = $('a', mylist).get(); 
    listitems.sort(function(x, y) { 
     if (isNaN(x.text) && isNaN(y.text)) { 
      var compA = $(x).text().toUpperCase(); 
      var compB = $(y).text().toUpperCase(); 
      return (compA < compB) ? -1 : 1; 
     } else { 
      return (x.text < y.text) ? -1 : 1;} 
     } 
    ); 
    $.each(listitems, function(i, itm) { 
     mylist.append(itm); 
    }); 
    }  
}); 

//Call this function to sort the list 
$("div#countries").sortList(); 

但是使用這個,數量在上面,有時整理來了,有時不排序(不知道爲什麼),&字母數字後完全排序。我試過搜索許多論壇排序&分組完全,但在jQuery中,我無法做到這一點(我想念C#LinQ):|請幫忙。

編輯1:

按照下面的建議,我用這個代碼,但我的數值以字符串形式也即將,就是數字沒有得到整理出來的原因。

代碼:

$(function() { 
    $.fn.sortList = function() { 
     debugger; 
    var mylist = $(this); 
    var listitems = $('a', mylist).get(); 
    listitems.sort(function(x, y) { 
     if($.isNumeric(x.text)){ 
      x.text = parseInt(x.text); 
     } 
     if($.isNumeric(y.text)){ 
      y.text = parseInt(y.text); 
     } 

     var a = Number(x.text); 
     var b = Number(y.text); 
     if (isNaN(a)) { 
        if (isNaN(b)) { 
         var compA = x.text.toUpperCase(); 
         var compB = y.text.toUpperCase(); 
         return (compA < compB) ? -1 : 1; 
        } else { 
         return -1; 
        } 
       } 
     else{ 
        if (isNaN(b)) { 
         return 1; 
        } else { 
         return a - b; 
       } 
      } 
     }); 

    $.each(listitems, function(i, itm) { 
     mylist.append(itm); 
    }); 
    }  
}); 

回答

0

的問題是,isNaN需要數字,而你提供的字符串。 另外,您並不認爲x是一個數字,而y是一個字符串,反之亦然。

你應該使用這個比較:

function compare(x, y) { 
    var a = Number(x.text); 
    var b = Number(y.text); 
    if (isNaN(a)) { 
     if (isNaN(b)) { 
      var compA = x.text.toUpperCase(); 
      var compB = y.text.toUpperCase(); 
      return (compA < compB) ? -1 : 1; 
     } else { 
      return -1; 
     } 
    } else { 
     if (isNaN(b)) { 
      return 1; 
     } else { 
      return a - b; 
     } 
    } 
} 
+0

只要找到了很多的調試,因爲它們是用「」來(以字符串形式)現在還沒有整理數字後:|任何幫助? – user3458749

+0

根據您的建議和我發現的問題,我正在編輯我的更新代碼的問題。 – user3458749

+0

你可以給一個例子(例如jsfiddle或類似的東西),它不工作? – Djizeus