programing

jQuery 테이블 정렬

elecom 2023. 8. 1. 20:18
반응형

jQuery 테이블 정렬

4개의 열로 구성된 매우 간단한 HTML 테이블이 있습니다.

Facility Name, Phone #, City, Specialty

사용자가 시설 이름과 도시만 기준으로 정렬할 수 있기를 원합니다.

jQuery를 사용하여 코드화하려면 어떻게 해야 합니까?

저는 우연히 이것을 발견했고, 2센트를 기부하려고 생각했습니다.오름차순을 정렬하려면 열 머리글을 클릭하고 내림차순을 정렬하려면 다시 클릭합니다.

  • Chrome, Firefox, Opera 및 IE(8)에서 작동합니다.
  • JQuery만 사용
  • 영숫자 정렬 - 오름차순 및 내림차순

$('th').click(function(){
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc){rows = rows.reverse()}
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index)
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
table, th, td {
    border: 1px solid black;
}
th {
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><th>Country</th><th>Date</th><th>Size</th></tr>
    <tr><td>France</td><td>2001-01-01</td><td>25</td></tr>
    <tr><td><a href=#>spain</a></td><td>2005-05-05</td><td></td></tr>
    <tr><td>Lebanon</td><td>2002-02-02</td><td>-17</td></tr>
    <tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>
    <tr><td>USA</td><td></td><td>-6</td></tr>
</table>

업데이트: 2018

만약 당신이 모든 종소리와 휘파람 소리를 피하고 싶다면, 는 이 간단한 플러그인을 제안해도 될까요?용도:

var table = $('table');

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

        var th = $(this),
            thIndex = th.index(),
            inverse = false;

        th.click(function(){

            table.find('td').filter(function(){

                return $(this).index() === thIndex;

            }).sortElements(function(a, b){

                if( $.text([a]) == $.text([b]) )
                    return 0;

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

            }, function(){

                // parentNode is the element we want to move
                return this.parentNode; 

            });

            inverse = !inverse;

        });

    });

그리고 데모.(정렬하려면 "도시" 및 "선택" 열 선택)

지금까지 사용한 것 중 가장 쉬운 것은 http://datatables.net/ 입니다.

놀랍도록 단순한... 및 를 DOM으로 .<thead>그리고.<tbody>그렇지 않으면 작동하지 않을 것입니다.그게 유일한 차야.

AJAX 등에 대한 지원도 있습니다.모든 좋은 코드 조각과 마찬가지로 모든 코드를 끄는 것도 매우 쉽습니다.하지만 당신은 당신이 사용할 수 있는 것에 놀랄 것입니다.처음에는 하나의 필드만 정렬하는 "맨손" 데이터 테이블로 시작했는데, 일부 기능이 제가 수행하는 작업과 실제로 관련이 있다는 것을 깨달았습니다.고객들은 새로운 기능을 좋아합니다.

ThemeRoller를 완벽하게 지원하기 위한 DataTables의 보너스 포인트...

테이블소터도 운이 좋았지만, 그것은 거의 쉽지 않고, 문서화되어 있지 않으며, 기능만 정상입니다.

우리는 이제 막 이 매끄러운 도구를 사용하기 시작했습니다: https://plugins.jquery.com/tablesorter/

다음 사이트에서 동영상을 사용할 수 있습니다. http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx

    $('#tableRoster').tablesorter({
        headers: {
            0: { sorter: false },
            4: { sorter: false }
        }
    });

간단한 테이블과 함께

<table id="tableRoster">
        <thead> 
                  <tr>
                    <th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
                    <th>User</th>
                    <th>Verified</th>
                    <th>Recently Accessed</th>
                    <th>&nbsp;</th>
                  </tr>
        </thead>

제 대답은 "조심하세요"입니다.많은 jQuery 테이블 정렬 추가 기능은 사용자가 브라우저에 전달한 내용만 정렬합니다.대부분의 경우 테이블은 동적 데이터 집합이며 잠재적으로 수십억 줄의 데이터를 포함할 수 있습니다.

열이 4개밖에 없다고 하지만 더 중요한 것은 몇 개의 행에 대해서는 언급하지 않는다는 것입니다.

실제 데이터베이스 테이블에 100,000개의 행이 포함되어 있다는 것을 알고 데이터베이스에서 브라우저로 5000개의 행을 전달한다면, 제 질문은 테이블을 정렬할 수 있게 만드는 것이 무슨 의미가 있는가 하는 것입니다.올바른 정렬을 수행하려면 쿼리를 데이터베이스로 다시 보내고 데이터베이스(데이터 정렬을 위해 실제로 설계된 도구)에서 정렬을 수행하도록 해야 합니다.

하지만 당신의 질문에 직접적으로 대답하자면, 제가 본 최고의 정렬 추가 기능은 잉그리드입니다.제가 이 추가 기능을 좋아하지 않는 이유는 여러 가지가 있습니다("불필요한 벨과 휘파람.Ajax를 사용하고 정렬하기 전에 모든 데이터를 이미 전달했다고 가정하지 않는 것이 종류 면에서 가장 좋은 기능의 종류는 Ajax입니다.

저는 이 답변이 아마도 당신의 요구 사항에 비해 과도하다는 것을 알고 있지만, 제 분야의 개발자들이 이 점을 간과할 때 짜증이 납니다.그래서 다른 사람이 알아줬으면 좋겠어요.

이제 좀 나아졌어요.

이것은 나이스 테이블 정렬 방법:

$(document).ready(function () {
                $('th').each(function (col) {
                    $(this).hover(
                            function () {
                                $(this).addClass('focus');
                            },
                            function () {
                                $(this).removeClass('focus');
                            }
                    );
                    $(this).click(function () {
                        if ($(this).is('.asc')) {
                            $(this).removeClass('asc');
                            $(this).addClass('desc selected');
                            sortOrder = -1;
                        } else {
                            $(this).addClass('asc selected');
                            $(this).removeClass('desc');
                            sortOrder = 1;
                        }
                        $(this).siblings().removeClass('asc selected');
                        $(this).siblings().removeClass('desc selected');
                        var arrData = $('table').find('tbody >tr:has(td)').get();
                        arrData.sort(function (a, b) {
                            var val1 = $(a).children('td').eq(col).text().toUpperCase();
                            var val2 = $(b).children('td').eq(col).text().toUpperCase();
                            if ($.isNumeric(val1) && $.isNumeric(val2))
                                return sortOrder == 1 ? val1 - val2 : val2 - val1;
                            else
                                return (val1 < val2) ? -sortOrder : (val1 > val2) ? sortOrder : 0;
                        });
                        $.each(arrData, function (index, row) {
                            $('tbody').append(row);
                        });
                    });
                });
            });
            table, th, td {
            border: 1px solid black;
        }
        th {
            cursor: pointer;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
        <tr><th>id</th><th>name</th><th>age</th></tr>
        <tr><td>1</td><td>Julian</td><td>31</td></tr>
        <tr><td>2</td><td>Bert</td><td>12</td></tr>
        <tr><td>3</td><td>Xavier</td><td>25</td></tr>
        <tr><td>4</td><td>Mindy</td><td>32</td></tr>
        <tr><td>5</td><td>David</td><td>40</td></tr>
    </table>

바이올린은 다음 위치에서 찾을 수 있습니다.
https://.net/e3s84Luw/https://jsfiddle.net/e3s84Luw/

설명은 https://www.learningjquery.com/2017/03/how-to-sort-html-table-using-jquery-code 에서 확인할 수 있습니다.

저는 이 수락된 답변이 마음에 들지만, HTML을 정렬해야 하고 정렬 방향을 나타내는 아이콘을 추가할 필요가 없는 경우는 거의 없습니다.수락 답변의 사용 예를 사용하여 프로젝트에 부트스트랩을 추가하고 다음 코드를 추가하여 빠르게 수정했습니다.

<div></div>

의 각각내에 에.<th>아이콘을 설정할 수 있습니다.

setIcon(this, inverse);

승인된 답변의 Usage(사용법)에서 다음과 같이 입력합니다.

th.click(function () {

setIcon 메서드를 추가하면 다음과 같습니다.

function setIcon(element, inverse) {

        var iconSpan = $(element).find('div');

        if (inverse == false) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-up');
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-down');
        }
        $(element).siblings().find('div').removeClass();
    }

데모가 작동하려면 Firefox 또는 IE에서 데모를 실행하거나 Chrome의 MIME 유형 검사를 비활성화해야 합니다.이는 승인된 답변에 의해 연결된 sortElements Plugin을 외부 리소스로 사용합니다.조심해요!

다음은 사용할 차트를 결정하는 데 도움이 될 수 있는 차트입니다. http://blog.sematext.com/2011/09/19/top-javascript-dynamic-table-libraries/

이것은 브라우저를 중단시키지 않으며, 추가로 쉽게 구성할 수 있습니다.

var table = $('table');

$('th.sortable').click(function(){
    var table = $(this).parents('table').eq(0);
    var ths = table.find('tr:gt(0)').toArray().sort(compare($(this).index()));
    this.asc = !this.asc;
    if (!this.asc)
       ths = ths.reverse();
    for (var i = 0; i < ths.length; i++)
       table.append(ths[i]);
});

function compare(idx) {
    return function(a, b) {
       var A = tableCell(a, idx), B = tableCell(b, idx)
       return $.isNumeric(A) && $.isNumeric(B) ? 
          A - B : A.toString().localeCompare(B)
    }
}

function tableCell(tr, index){ 
    return $(tr).children('td').eq(index).text() 
}

@Nick Grealy의 대답은 훌륭하지만, 가능성을 고려하지 않습니다.rowspan테이블 헤더 셀의 속성(다른 응답도 마찬가지일 수 있음).여기 그것을 고치는 @Nick Grealy의 답변의 개선이 있습니다. 답변을 바탕으로 (Andrew Orlov에게 감사합니다.)

저는 또한 그것을 교체했습니다.$.isNumeric이전 jQuery 버전에서 작동할 수 있도록 사용자 지정 버전(감사 @zad)과 함께 작동합니다.

활성화하려면 다음을 추가합니다.class="sortable"에게<table>꼬리표를 달다

$(document).ready(function() {

    $('table.sortable th').click(function(){
        var table = $(this).parents('table').eq(0);
        var column_index = get_column_index(this);
        var rows = table.find('tbody tr').toArray().sort(comparer(column_index));
        this.asc = !this.asc;
        if (!this.asc){rows = rows.reverse()};
        for (var i = 0; i < rows.length; i++){table.append(rows[i])};
    })

});

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index);
        return isNumber(valA) && isNumber(valB) ? valA - valB : valA.localeCompare(valB);
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() };

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function get_column_index(element) {
    var clickedEl = $(element);
    var myCol = clickedEl.closest("th").index();
    var myRow = clickedEl.closest("tr").index();
    var rowspans = $("th[rowspan]");
    rowspans.each(function () {
        var rs = $(this);
        var rsIndex = rs.closest("tr").index();
        var rsQuantity = parseInt(rs.attr("rowspan"));
        if (myRow > rsIndex && myRow <= rsIndex + rsQuantity - 1) {
            myCol++;
        }
    });
    // alert('Row: ' + myRow + ', Column: ' + myCol);
    return myCol;
};

James의 답변에 대해 나는 정렬 기능을 좀 더 보편적으로 변경할 것입니다.이렇게 하면 텍스트를 알파벳 순으로 정렬하고 숫자를 숫자처럼 정렬할 수 있습니다.

if( $.text([a]) == $.text([b]) )
    return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
    return $.text([a]) > $.text([b]) ? 
       inverse ? -1 : 1
       : inverse ? 1 : -1;
}
else{
    return parseInt($.text([a])) > parseInt($.text([b])) ? 
      inverse ? -1 : 1
      : inverse ? 1 : -1;
}

정렬, 필터 및 페이지를 제공하는 jQuery 플러그인(breadjs)을 사용할 수 있습니다.

HTML:

<table>
  <thead>
    <tr>
      <th sort='name'>Name</th>
      <th>Phone</th>
      <th sort='city'>City</th>
      <th>Speciality</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people">
      <td b-sort="name">{{person.name}}</td>
      <td>{{person.phone}}</td>
      <td b-sort="city">{{person.city}}</td>
      <td>{{person.speciality}}</td>
    </tr>
  </tbody>
</table>

JS:

$(function(){
  var data = {
    people: [
      {name: 'c', phone: 123, city: 'b', speciality: 'a'},
      {name: 'b', phone: 345, city: 'a', speciality: 'c'},
      {name: 'a', phone: 234, city: 'c', speciality: 'b'},
    ]
  };
  breed.run({
    scope: 'people',
    input: data
  });
  $("th[sort]").click(function(){
    breed.sort({
      scope: 'people',
      selector: $(this).attr('sort')
    });
  });
});

fiddle에 대한 작업 예제

저는 결국 닉의 답변(가장 인기가 많지만 받아들여지지 않음) https://stackoverflow.com/a/19947532/5271220 을 사용하게 되었습니다.

그리고 그것을 https://stackoverflow.com/a/16819442/5271220 과 결합했지만 프로젝트에 아이콘이나 폰타우섬을 추가하고 싶지 않았습니다.sort-column-asc/desc에 대한 CSS 스타일 나는 색상, 패딩, 둥근 테두리를 했습니다.

또한 분류 가능한 클래스를 제어할 수 있도록 클래스별로 변경했습니다.테이블이 두 개인 경우에도 나중에 유용하게 사용할 수 있지만 이를 위해 더 많은 수정 작업이 필요합니다.

본문:

 html += "<thead>\n";
    html += "<th></th>\n";
    html += "<th class=\"sort-header\">Name <span></span></i></th>\n";
    html += "<th class=\"sort-header\">Status <span></span></th>\n";
    html += "<th class=\"sort-header\">Comments <span></span></th>\n";
    html += "<th class=\"sort-header\">Location <span></span></th>\n";
    html += "<th nowrap class=\"sort-header\">Est. return <span></span></th>\n";
    html += "</thead>\n";
    html += "<tbody>\n"; ...

몸을 더 아래쪽으로

$("body").on("click", ".sort-header", function (e) {
    var table = $(this).parents('table').eq(0)
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    if (!this.asc) { rows = rows.reverse() }
    for (var i = 0; i < rows.length; i++) { table.append(rows[i]) }

    setIcon(e.target, this.asc);
});

함수:

function comparer(index) {
        return function (a, b) {
            var valA = getCellValue(a, index), valB = getCellValue(b, index)
            return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
        }
    }

    function getCellValue(row, index) {
        return $(row).children('td').eq(index).text()
    }

    function setIcon(element, inverse) {

        var iconSpan = $(element).find('span');

        if (inverse == true) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-asc');
            $(iconSpan)[0].innerHTML = " &#8593 " // arrow up
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('sort-column-desc');
            $(iconSpan)[0].innerHTML = " &#8595 " // arrow down 
        }

        $(element).siblings().find('span').each(function (i, obj) {
            $(obj).removeClass();
            obj.innerHTML = "";
        });
    }

HTML 테이블을 정렬하는 또 다른 접근법입니다. (W3 기준)JS HTML 정렬)

/* Facility Name */
$('#bioTable th:eq(0)').addClass("control-label pointer");
/* Phone # */
$('#bioTable th:eq(1)').addClass("not-allowed");
/* City */
$('#bioTable th:eq(2)').addClass("control-label pointer");
/* Specialty */
$('#bioTable th:eq(3)').addClass("not-allowed");


var collection = [{
  "FacilityName": "MinION",
  "Phone": "999-8888",
  "City": "France",
  "Specialty": "Genetic Prediction"
}, {
  "FacilityName": "GridION X5",
  "Phone": "999-8812",
  "City": "Singapore",
  "Specialty": "DNA Assembly"
}, {
  "FacilityName": "PromethION",
  "Phone": "929-8888",
  "City": "San Francisco",
  "Specialty": "DNA Testing"
}, {
  "FacilityName": "iSeq 100 System",
  "Phone": "999-8008",
  "City": "Christchurch",
  "Specialty": "gDNA-mRNA sequencing"
}]

$tbody = $("#bioTable").append('<tbody></tbody>');

for (var i = 0; i < collection.length; i++) {
  $tbody = $tbody.append('<tr class="item"><td>' + collection[i]["FacilityName"] + '</td><td>' + collection[i]["Phone"] + '</td><td>' + collection[i]["City"] + '</td><td>' + collection[i]["Specialty"] + '</td></tr>');
}
.control-label:after {
  content: "*";
  color: red;
}

.pointer {
  cursor: pointer;
}

.not-allowed {
  cursor: not-allowed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>

<table id="bioTable" class="w3-table-all">
  <thead>
    <tr>
      <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(1)')">Facility Name</th>
      <th>Phone #</th>
      <th onclick="w3.sortHTML('#bioTable', '.item', 'td:nth-child(3)')">City</th>
      <th>Specialty</th>
    </tr>
  </thead>
</table>

나의 투표! jquery.sortElements.js와 간단한 jquery.
아주 간단하고, 아주 쉬워요, 고마워요, ndhp...

            $('th').live('click', function(){

            var th = $(this), thIndex = th.index(), var table = $(this).parent().parent();

                switch($(this).attr('inverse')){
                case 'false': inverse = true; break;
                case 'true:': inverse = false; break;
                default: inverse = false; break;
                }
            th.attr('inverse',inverse)

            table.find('td').filter(function(){
                return $(this).index() === thIndex;
            }).sortElements(function(a, b){
                return $.text([a]) > $.text([b]) ?
                    inverse ? -1 : 1
                    : inverse ? 1 : -1;
            }, function(){
                // parentNode is the element we want to move
                return this.parentNode; 
            });
            inverse = !inverse;     
            });

데이마멜호라다도코디고
대구 한 마리가 더 낫습니다!항상 모든 Thin에 있는 모든 테이블에 대한 기능... 봐요!
데모

언급URL : https://stackoverflow.com/questions/3160277/jquery-table-sort

반응형