2012-06-20 4 views
1

처음 질문을 올렸을 때 실수를했기 때문에이 질문을 다시 게시합니다. 질문하기 전에 충분히 열심히 노력하지 않았습니다. 그리고 저에게 제 일을하도록 요청한 것에 대해 지역 사회에 사과하고 싶습니다.알파벳순으로 항목 정렬

div 안에 정렬되지 않은 목록을 사전 순으로 정렬하려고합니다. 목록 항목의 순서가 지정되지 않은 목록 내부는 아니지만 순서가 지정되지 않은 목록 자체. 내가 같이하기를 원하는

<div class="FindByCategory"> 
    <ul> 
     <li> B. This is the first list item in the second unordered list</li> 
     <li> B. This is the second list item in the second unordered list</li> 
    </ul> 
    <ul> 
     <li> A. This is the first list item in the first unordered list</li> 
     <li> A. This is the second list item in the first unordered list</li> 
    </ul> 
</div> 

:

<div class="FindByCategory"> 
    <ul> 
     <li> A. This is the first list item in the first unordered list</li> 
     <li> A. This is the second list item in the first unordered list</li> 
    </ul> 
    <ul> 
     <li> B. This is the first list item in the second unordered list</li> 
     <li> B. This is the second list item in the second unordered list</li> 
    </ul> 
</div> 

이것은 내가 지금까지 무엇을했는지된다

는 같은 HTML이 모습입니다

<script> 
     function sortUnorderedList(div.FindByCategory, sortDescending) { 
    if(typeof div.FindByCategory == "string") 
    div = document.getElementById(div.FindByCategory); 
    var uls = ul.getElementsByTagName("UL"); 
    var vals = []; 
    for(var i = 0, l = uls.length; i < l; i++) 
    vals.push(uls[i].innerHTML); 
    vals.sort(); 
    for(var i = 0, l = uls.length; i < l; i++) 
    uls[i].innerHTML = vals[i]; 
} 
$(function(){ 
    FindByCategory() 
    } 
    </script> 

답변

1

모든 DOM 노드를 정렬 할 때, 세 가지 간단한 단계가 있습니다 :

  1. 그것은 쉽게 접근 재산없는 경우 (정렬되어 그들 중 어떤 부분과 함께 정렬하는 노드의 배열을 구축).
  2. 배열을 정렬하십시오.
  3. 새 주문을 기반으로 DOM 트리를 다시 작성하십시오.

이 경우 정렬 할 노드는 #FindByCategory > ul과 일치하며 실제로 텍스트 내용별로 정렬됩니다. 그래서 : - 단계를 설명하기위한 감사

var qsa = document.querySelectorAll("#FindByCateory > ul"), l = qsa.length, i, arr = []; 
for(i=0; i<l; i++) { 
    arr[i] = [qsa[i],qsa[i].textContent || qsa[i].innerText]; 
    // the text content is not readily accessible, since it depends on the browser 
} 
// now sort the array: 
arr.sort(function(a,b) {return a[1] < b[1] ? -1 : (a[1] == b[1] ? 0 : 1);}); 
// and now re-append them 
for(i=0; i<l; i++) { 
    arr[i][0].parentNode.appendChild(arr[i][0]); 
    // by re-appending the nodes, they will emerge sorted 
} 
+0

을보십시오! –

1

정말이 대답 같은
<script type="text/javascript"> 

       var array = new Array(); 

       for(var i = 0 ; i<4 ; i++){ 

        var string = $("li:eq("+i+")").text(); 
        array[i] = string; 

       } 

       array.sort(); 

       alert(array); 


      </script> 
관련 문제