2012-03-02 7 views
2

다음과 같은 데이터 테이블이 있으며 개별 정렬 오름차순 및 내림차순 버튼이 있습니다. 내가 jQuery 플러그인 "jQuery.fn.sort"여기 James Padolseyjquery를 사용하여 오름차순 및 내림차순 정렬 맞춤 데이터 테이블 정렬

을 사용하고 는

enter image description here

내가 각 대령하지만 작동하지 않습니다에 정렬 추가 할 작업 예를

http://jsbin.com/alawub/2/edit입니다 이것에 대한 다른 대안 솔루션 위의 JS 코드를 검토하십시오.

아주 쉽게 http://www.kryogenix.org/code/browser/sorttable/ 사용하고 설치하기 -

+3

휠을 다시 발명하는 이유는 무엇입니까? 시도해보십시오 http://datatables.net –

+0

그것의 특정 요구 사항 –

+1

그 플러그인을 사용해야합니까? 전에 http://tablesorter.com/에서 플러그인을 사용했는데 잘 작동합니다. –

답변

5

당신은 너무 여러 번 클릭 핸들러를 추가 :

$('th') 
    .wrapInner('<span title="sort this column"/>') 
    .each(function(){ 
     ... 
     $('#accending_1,#accending_2').click(function(e){ 

이것이 할 것입니다 것은 모든 일에 대해, 그리고 4 개 번째 태그의 두 행이, 아이디 accending_1와 요소에 클릭 처리기를 추가 및 accending_2. 그러면 각 버튼에 8 개의 클릭 핸들러가 추가됩니다!

이 문제를 해결할 수있는 방법은 다양합니다. 대신 각 버튼의 사용 클래스에 대한 특정 아이디의를 가진 헤더에 그들을 상대 찾기의 :

$('th') 
    .wrapInner('<span title="sort this column"/>') 
    .each(function(){ 

     $('.accending', this).click(

example

참고 현재 TH의 후손으로 선택을 제한하는 마지막 줄에 this 매개 변수입니다. 그것은 여전히 ​​TH의 최상위 행에 대한 검색을 수행 할 것입니다.

이. 그냥 버튼을 직접 검색하고 자신들이 무엇을 열 해결 아마 더 나은

$('.accending, .accending') 
    .wrapInner('<span title="sort this column"/>') 
    .click(function(e){ 
     console.log("click"); 
     var th = $(this).closest('th'), 
     thIndex = th.index(); 
     table.find('td') 
     .filter(function(){ 
      return $(this).index() === thIndex; 
     }) 
     .sort(
      function(a, b){ 
      return $.text([a]) > $.text([b]); 
      }, function(){ 
      // parentNode is the element we want to move 
      return this.parentNode; 
      } 
     ); 
    }); 
    $('.decending, .decending') 

example

상기 코드의 중복을 많이하고, HTML은 여전히있다.

클릭 핸들러는 거의 동일하므로 정렬 기능 만 전달하면됩니다.

//This function returns another function which is a click handler. 
    //It takes the sort function as a parameter. 
    function createClickHandler(sortFunction){ 
    return function(e){ 
     var th = $(e.target).closest('th'), 
     thIndex = th.index(); 
     console.log(th); 
     table.find('td') 
     .filter(function(){ 
      return $(this).index() === thIndex; 
     }) 
     .sort(sortFunction, function(){ 
      // parentNode is the element we want to move 
      return this.parentNode; 
      } 
     ); 
    }; 
    } 

    $('.accending, .accending') 
    .wrapInner('<span title="sort this column"/>') 
    .click(createClickHandler(function(a, b){ 
     return $.text([a]) > $.text([b]); 
     }) 
    ); 
    $('.decending, .decending') 
    .wrapInner('<span title="sort this column"/>') 
    .click(createClickHandler(function(a, b){ 
     return $.text([a]) < $.text([b]); 
     }) 
    ); 

example

html로

도 조금 정리 될 수있다. 버튼의 태그는 모두 동일하므로 자바 스크립트에서 삽입 핸들러를 검색 할 필요없이 직접 삽입 할 수 있습니다. 다시 열 머리글을 반복하므로 열 번호를 얻는 방법을 정리할 수 있습니다. 그리고 마지막으로 두 개의 다른 정렬 함수를 전달하는 것은 약간 낭비이므로 방향 매개 변수를 대신 전달해 보겠습니다. I는 역 변수를 제거

example


참고

//This function returns another function which is a click handler. 
    //It takes the sort function as a parameter. 
    function createClickHandler(column, isAccending){ 
    return function(e){ 
     table.find('td') 
     .filter(function(){ 
      return $(this).index() === column; 
     }) 
     .sort(function(a, b){ 
      var order = $.text([a]) > $.text([b]); 
      return isAccending ? order : !order; 
     }, function(){ 
      // parentNode is the element we want to move 
      return this.parentNode; 
     }) 
     ; 
    }; 
    } 

    $('#controls th').each(function(column,item){ 
    //Note we get the column index for for free with the each function 
    $(this) 
     .append($('<a title="sort this column" href="#">Ascending</a>') 
     .click(createClickHandler(column, true)) 
    ) 
     .append('&nbsp;&nbsp;') 
     .append($('<a title="sort this column" href="#">Decending</a>') 
     .click(createClickHandler(column, false)) 
    ) 
     ; 
    }); 
. 그것은 결코 사용되지 않았습니다.

return $.text([a]) > $.text([b]) 
    inverse ? -1 : 1 
    ; 

나는이 일을했지만 실제로 인해 automatic semicolon insertion에 첫 번째 줄에 반환의 사상 모르겠어요. 다음과 같이 해석됩니다.

return $.text([a]) > $.text([b]); 
    inverse ? -1 : 1; 

그래서 역수는 데드 코드입니다. 그것은 자바 스크립트의 나쁜 비트 중 하나이며 아주 분명하지 않습니다. jsbin이 세미콜론 누락에 대해 경고했습니다. 여기에 코드를 제출하기 전에 항상 오류/경고를 수정해야합니다.

+0

자세한 답변과 설명에 감사드립니다.하지만 마지막 열에는 Acc를 정렬 할 때 문제가 있다고 생각합니다. [123, 324, 1234] 일 때 [123, 1234, 324] 순서가 올바르지 않습니다.이 특정 버그의 원인은 무엇일까요? –

+0

@WasimShaikh, sort 함수는 숫자가 아닌 텍스트로 정렬합니다. –

+0

@WasimShaikh 다음 질문 중 하나의 정렬 함수 중 하나를 사용하십시오. http://stackoverflow.com/questions/2802341/natural-sort-of-text-and-numbers-javascript http://stackoverflow.com/questions/ 2802341/natural-sort-of-text-and-numbers-javascript를 사용하여'order' 변수에 할당하거나 직접 작성하십시오. 귀하의 데이터에 가장 적합한 정렬 알고리즘을 가장 잘 판단 할 수 있습니다. –

0

은 정말 kryogenix.org에서 "sorttable"스크립트를 사랑 해요.

0

나는 코드 작업을 수행했습니다. 여기에 코드입니다, 또한 당신은 jsbin에서 테스트 할 수 있습니다 http://jsbin.com/alawub/15/

자바 스크립트 :

$(document).ready(function(){ 

    var $table = $('table'); 
    $table.on('click', 'th a.accending_1, th a.decending_1', function(e){ 
    var th = $(e.target).parent('th'), 
    thIndex = th.index(), 
    direction = $(e.target).attr('class').match('accending')?'A':'D', 
    sortDir = th.data('direction'+thIndex); 
    if(sortDir && sortDir == direction) return; 

     $table.find('td').filter(function(){ 
       return $(this).index() === thIndex; 
      }).sort(function(a, b){ 
       if(direction == 'D') 
        return $.text([a]) > $.text([b]) ? -1 : 1; 
       else 
        return $.text([a]) > $.text([b]) ? 1 : -1; 

      }, function(){ 
       // parentNode is the element we want to move 
       return this.parentNode; 
      }); 
     th.data('direction'+thIndex, direction); 
    }); 

}); 

HTML : (A의 단지 수정 클래스) jsbin 이상

<th id="facility_header1"> 
     Table Header 1<br /> 
     <a href="#" class="accending_1">Accending</a>&nbsp;&nbsp; 
     <a href="#" class="decending_1">Decending</a> 
    </th> 
    <th id="facility_header2"> 
     Table Header 2<br /> 
     <a href="#" class="accending_1">Accending</a>&nbsp;&nbsp; 
     <a href="#" class="decending_1">Decending</a> 
    </th> 

근무 예 : http://jsbin.com/alawub/15/

0

나는 tablesorter이 필요한 기능을 제공한다고 생각합니다. 텍스트 및 숫자 열을 확실히 처리합니다. 테이블을 동적으로 업데이트하는 데는 문제가 있지만 훌륭한 픽스가 here입니다.

0

JS Bin에서 4 개의 경고를 볼 수 있습니다.

줄 67 : return $ .text ([a])> $ .text ([b]) --- 누락 된 세미콜론.
줄 68 : 반대입니까? -1 : 1 --- 할당 또는 함수 호출이 필요하고 대신 표현식을 보았습니다.
줄 82 : return $ .text ([a]) < $ .text ([b]) --- 누락 된 세미콜론.
라인 83 : 반대입니까? 1 : -1; --- 할당이나 함수 호출을 기대하고 대신 표현식을 보았습니다.

이러한 오류를 수정하면 예상되는 결과를 얻을 수 있기를 바랍니다.

관련 문제