상세 컨텐츠

본문 제목

jquery 이용하여 테이블 소팅하기, Table Sort / 테이블정렬

IT공부방/jQuery, ajax, java

by 동해둘리 2023. 6. 19. 11:43

본문

반응형

jquery를 이용하여 테이블소팅/ 테이블정렬

jquery를 이용하여 테이블을 소팅하는 코드입니다. 상단 제목 부분을 클릭하면 해당 항목을 기준으로 정렬되어 표시됩니다. 

 

배열에 대한 이해가 있으시다면 이해하기 쉬우실 꺼에요. comparator 함수가 값을 비교하여 결과를 전달하면, rows 라는 array에 값을 넣어놓고 reverse()함수를 이용하여 배열내의 값을 정렬하는 코드입니다. 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<!DOCTYPE html>
<html>
<head>  
</head>
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<meta charset="utf-8" />
<style>
.styled-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ddd;
}
 
.styled-table thead th {
  padding: 12px 15px;
  text-align: left;
  background-color: #f8f8f8;
  border-bottom: 1px solid #ddd;
  cursor: pointer;
}
 
.styled-table tbody td {
  padding: 12px 15px;
}
 
.styled-table tbody tr:nth-child(even) {
  background-color: #f2f2f2;
}
 
.styled-table tbody tr:hover {
  background-color: #ddd;
}
 
</style>
<body>
  <table id="myTable" class="styled-table">
    <thead>
      <tr>
        <th>이름</th>
        <th>나이</th>
        <th>도시</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>John</td>
        <td>25</td>
        <td>New York</td>
      </tr>
      <tr>
        <td>Bob</td>
        <td>30</td>
        <td>London</td>
      </tr>
      <tr>
        <td>Alice</td>
        <td>20</td>
        <td>Paris</td>
      </tr>
    </tbody>
  </table>
  
  <script language = "javascript">
$(document).ready(function() {
  $("th").click(function() {
    let table = $(this).parents("table").eq(0);
    let rows = table.find("tr:gt(0)").toArray().sort(comparator($(this).index()));
    this.asc = !this.asc;
    if (!this.asc) {
      rows = rows.reverse();
    }
    for (let i = 0; i < rows.length; i++) {
      table.append(rows[i]);
    }
  });
 
  function comparator(index) {
    return function(a, b) {
      let aValue = getCellValue(a, index);
      let bValue = getCellValue(b, index);
      if (index === 1) {
        // 나이를 숫자로 변환하여 정렬
        aValue = parseInt(aValue);
        bValue = parseInt(bValue);
      }
      if (aValue < bValue) return -1;
      if (aValue > bValue) return 1;
      return 0;
    };
  }
 
  function getCellValue(row, index) {
    return $(row).children("td").eq(index).text();
  }
});
 
 
  </script>  
</body>
</html>
 
cs
반응형

관련글 더보기

댓글 영역