对象数组排序,利用jquery

聆听蘭 2015-12-17

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  2.   
  3. <html>  
  4.   <head>  
  5.     <title>jQuery数组和字符串--对象数组排序</title>  
  6.     <script type="text/javascript" src="../jquery-1.3.2.min.js"></script>  
  7.   
  8.     <script type="text/javascript">  
  9.   
  10.     <!--  
  11.     $(  
  12.         function()  
  13.         {  
  14.             var students =[  
  15.                 {'sid':'ST001','sname':'张三','sage':18},  
  16.                 {'sid':'ST004','sname':'赵六','sage':23},  
  17.                 {'sid':'ST002','sname':'李四','sage':42},  
  18.                 {'sid':'ST003','sname':'王五','sage':35}  
  19.             ];  
  20.             //表格显示  
  21.             $.each(students,  
  22.                 function(index, value)  
  23.                 {  
  24.                     $('#ia').append('<tr><td>' + value.sid +   
  25.                         '</td><td>' + value.sname +   
  26.                         '</td><td>' + value.sage + '</td></tr>');  
  27.                 }  
  28.             );  
  29.             //按照SID排序  
  30.             var sidOrder = students.sort(  
  31.                 function(a, b)  
  32.                 {  
  33.                     if(a.sid < b.sid) return -1;  
  34.                     if(a.sid > b.sid) return 1;  
  35.                     return 0;  
  36.                 }  
  37.             );  
  38.             $.each(sidOrder,  
  39.                 function(index, value)  
  40.                 {  
  41.                     $('#ib').append('<tr><td>' + value.sid +  
  42.                         '</td><td>' + value.sname +   
  43.                         '</td><td>' + value.sage + '</td></tr>')  
  44.                 }  
  45.             );  
  46.             //按照SAGE排序  
  47.             var sageOrder = students.sort(  
  48.                 function(a, b)  
  49.                 {  
  50.                     return (a.sage - b.sage);  
  51.                 }  
  52.             );  
  53.             $.each(sageOrder,  
  54.                 function(index, value)  
  55.                 {  
  56.                     $('#ic').append('<tr><td>' + value.sid +  
  57.                         '</td><td>' + value.sname +   
  58.                         '</td><td>' + value.sage + '</td></tr>')  
  59.                 }  
  60.             );  
  61.         }  
  62.     );  
  63.     //-->  
  64.     </script>  
  65.   </head>  
  66.   <body>  
  67.     <h5>未排序对象数组:</h5>  
  68.     <table id='ia' border="1"></table>  
  69.   
  70.     <h5>按照SID排序对象数组:</h5>  
  71.     <table id='ib' border="1"></table>  
  72.   
  73.     <h5>按照SAGE排序对象数组:</h5>  
  74.     <table id='ic' border="1"></table>  
  75.   
  76.   </body>  
  77. </html>

相关推荐