2012-06-20 184 views
1

我重新发布了这个问题,因为我第一次发布商品时犯了一个错误:在询问之前我没有足够努力。我想向社区道歉,要求它为我做我的工作按字母顺序对商品排序

我想按字母顺序排列div中的无序列表。不是列表项在无序列表中,而是无序列表本身。

这是HTML的样子:

<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> 

这是我迄今所做的:

<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>