排序
根据data-sale进行排序,data-sale 由小到大 排li的位置
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 2 "http://www.w3.org/TR/html4/strict.dtd"> 3 4 <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title>排序</title> 8 <meta name="author" content="Administrator" /> 9 <!-- Date: 2014-12-19 --> 10 <script> 11 window.onload=function(){ 12 var oUl=document.getElementsByTagName('ul')[0]; 13 var aLi=document.getElementsByTagName('li'); 14 var json={ 15 'className':[], 16 'data-sale':[], 17 'text':[] 18 }; 19 for(var i=0;i<aLi.length;i++){ 20 json.className.push( aLi[i].className ); 21 json['data-sale'].push( aLi[i].getAttribute('data-sale') ); 22 json['text'].push( aLi[i].innerHTML ); 23 } 24 25 //分别将数组 复制到新的数组,以便对应各个数组的index 26 var arr2=[]; 27 var arr3=[]; 28 var arr4=[] 29 for(var i=0;i<json['data-sale'].length;i++){ 30 arr2.push( json['data-sale'][i] ); 31 arr3.push( json['className'][i] ); 32 arr4.push( json['text'][i] ); 33 } 34 35 //对data-sale进行排序 36 json['data-sale'].sort(function (a,b){ 37 return a-b 38 }); //data-sale 排好序了 1,2,3,3,5,8 39 40 41 42 document.onclick=function(){ 43 for( var i=0;i< json['data-sale'].length;i++ ){ 44 //json['data-sale'][i] = json['data-sale'][i] ; 45 json['className'][i] = arr3[ indexofArr(arr2, json['data-sale'][i]) ]; 46 json['text'][i] = arr4[ indexofArr(arr2, json['data-sale'][i]) ]; 47 48 aLi[i].className=json['className'][i]; 49 aLi[i].setAttribute('data-sale', json['data-sale'][i]) 50 aLi[i].innerHTML = json['text'][i] 51 } 52 } 53 54 console.log( arr3 ); 55 console.log( arr4 ); 56 } 57 58 /**检查 某个元素v 在数组中是否存在,存在返回i (下标) 不存在返回-1**/ 59 function indexofArr(arr,v){ 60 for(var i=0;i<arr.length;i++){ 61 if(arr[i]==v){ 62 return i //存在 63 } 64 } 65 66 return -1 //不存在 67 } 68 69 </script> 70 </head> 71 <body> 72 <ul> 73 <li class="pos_1" data-sale='5'>5-aaa</li> 74 <li class="pos_2" data-sale='3'>3-aaa</li> 75 <li class="pos_3" data-sale='2'>2-aaa</li> 76 <li class="pos_4" data-sale='1'>1-aaa</li> 77 <li class="pos_5" data-sale='8'>8-aaa</li> 78 <li class="pos_6" data-sale='3'>3-aaa</li> 79 </ul> 80 </body> 81 </html>