CSS&JS/⚡Thinkers

[JS] thead의 th를 누르면 그 항목에 맞춰 table sort 되게 하기

arancia_ 2022. 3. 31. 17:32

여기서 thead의 th인 이름 또는 나이를 누르면 tbody의 cell들이 그 값에 맞게 정렬되도록 해보자

 

이름을 눌러 정렬시킨 경우

 

나이를 눌러 정렬시킨 경우

 

해결 방법 :

  1. 우선 클릭한 th의 cellIndex를 알아오고
  2. 해당 tbody의 cellIndex에 해당하는 셀 안의 값끼리 비교하여
  3. tr을 insertBefore를 사용하여 옮겨줄것이다.

여기선 name,age로 해버렸지만 좀 더 범용성 있게 한다면 str과 num으로 하는게 맞다 ^^ 근데 포스팅 수정하기 귗낳음 ㅋ 

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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<!DOCTYPE html>
<html lang="ko">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>table sort</title>
    <style>
        table{border-spacing:0;border-collapse:separate;}
        th,td{border:1px solid #000; padding:1em 2em;}
        thead th{background:#eee; cursor:pointer;}
    </style>
</head>
 
<body>
    <h1>뜬금무 table sort</h1>
 
    <table>
        <thead>
            <tr>
                <th data-sort="name">이름</th>
                <th data-sort="age">나이</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>모이라 오디오런</th>
                <td>48</td>
            </tr>
            <tr>
                <th>Din Djarin</th>
                <td>38</td>
            </tr>
            <tr>
                <th>Luke Skywalker</th>
                <td>28</td>
            </tr>
            <tr>
                <th>Moira O'Deorain</th>
                <td>48</td>
            </tr>
            <tr>
                <th>Siebren De Kuiper</th>
                <td>62</td>
            </tr>
            <tr>
                <th>Jamison Fawkes</th>
                <td>25</td>
            </tr>
            <tr>
                <th>시브런 드 카위퍼</th>
                <td>62</td>
            </tr>
            <tr>
                <th>다다다다다다다</th>
                <td>11111</td>
            </tr>
            <tr>
                <th>가가가가</th>
                <td>99999</td>
            </tr>
            <tr>
                <th>나나</th>
                <td>3333</td>
            </tr>
            <tr>
                <th>aaaa</th>
                <td>11111</td>
            </tr>
            <tr>
                <th>Aaaa</th>
                <td>99999</td>
            </tr>
            <tr>
                <th>bbbb</th>
                <td>3333</td>
            </tr>
        </tbody>
    </table>
    <script>
        window.addEventListener('click', e => {
            if (e.target.dataset.sort) { table_sort(e.target); }
        });
 
        function table_sort(target) {
            const $tbody = target.parentElement.parentElement.nextElementSibling;
            for(let i=0; i<$tbody.children.length; i++){
                sort_func(target);
            }
        }//table_sort
 
        function sort_func(target) {
            const cidx = target.cellIndex;
            const $tbody = target.parentElement.parentElement.nextElementSibling;
            for (let i = 0; i < $tbody.children.length - 1; i++) {
                const $curr = $tbody.children[i].children[cidx];
                const $next = $tbody.children[i + 1].children[cidx];
                let val_curr = $curr.innerText;
                let val_next = $next.innerText;
                let predi;
                switch(target.dataset.sort){
                    case "name" :
                        val_curr = val_curr[0].toLowerCase();
                        val_next = val_next[0].toLowerCase();
                        break;
                        
                    case "age" :
                        val_curr = parseInt(val_curr);
                        val_next = parseInt(val_next);
                        break;
                }
                if (val_curr > val_next) {
                    $tbody.insertBefore($curr.parentElement, $next.parentElement.nextElementSibling);
                }
            }//for-i
        }//sort_func
    </script>
</body>
 
</html>
cs