2011-07-18 3 views
8

클래스 이름을 기준으로 테이블 행을 다시 정렬하려고합니다.
다음은 제 HTML 코드입니다. 마찬가지로 먼저 표시해야 클래스 이름 A1으로 이제클래스 이름을 기준으로 테이블 행 정렬

<table> 
<tr class="a4"><td>4</td></tr> 
<tr class="a6"><td>6</td></tr> 
<tr class="a1"><td>1</td></tr> 
<tr class="a2"><td>2</td></tr> 
<tr class="a5"><td>5</td></tr> 
<tr class="a3"><td>3</td></tr> 
</table> 

, A2 초 .. 등

누군가가 나에게 도와주세요

당신과 같은 것으로 this 플러그인을 사용할 수

답변

12

I 외부 플러그인을 사용하지 않으려면 match()을 사용하여 클래스 이름에서 숫자를 추출하고 내장 된 sort() 메소드를 사용하여 요소를 정렬 할 수 있습니다.

여기에서, 당신은 테이블 행의 순서를 append()을 사용할 수 있습니다 (그 다음 테이블에서 각 행을 제거합니다 적절한 위치에 다시 추가) :

$("table").append($("tr").get().sort(function(a, b) { 
    return parseInt($(a).attr("class").match(/\d+/), 10) 
     - parseInt($(b).attr("class").match(/\d+/), 10); 
})); 

당신은 this fiddle에 결과를 볼 수 있습니다 .

+0

놀라운 아이디어 .. 감사합니다 .--) – Reddy

+0

감사합니다. – zero8

3

:

여기
jQuery.fn.sortElements = (function(){ 

    var sort = [].sort; 

    return function(comparator, getSortable) { 

     getSortable = getSortable || function(){return this;}; 

     var placements = this.map(function(){ 

      var sortElement = getSortable.call(this), 
       parentNode = sortElement.parentNode, 

       // Since the element itself will change position, we have 
       // to have some way of storing its original position in 
       // the DOM. The easiest way is to have a 'flag' node: 
       nextSibling = parentNode.insertBefore(
        document.createTextNode(''), 
        sortElement.nextSibling 
       ); 

      return function() { 

       if (parentNode === this) { 
        throw new Error(
         "You can't sort elements if any one is a descendant of another." 
        ); 
       } 

       // Insert before flag: 
       parentNode.insertBefore(this, nextSibling); 
       // Remove flag: 
       parentNode.removeChild(nextSibling); 

      }; 

     }); 

     return sort.call(this, comparator).each(function(i){ 
      placements[i].call(getSortable.call(this)); 
     }); 

    }; 

})(); 
// do the sorting 
$('tr').sortElements(function(a, b){ 
    return $(a).attr('class') > $(b).attr('class') ? 1 : -1; 
}); 

바이올린 : http://jsfiddle.net/ZV5yc/1/

+0

나는 이것이 더 높은 등급 덕분에 감사하다고 생각합니다. – zero8

+0

http://jsfiddle.net/zeroeight/ZV5yc/50/ – zero8