웹 페이지에서 테이블 형식의 데이터를 표시하고 정렬할 수 있는 방법에 대해 알아보겠습니다. TableSorter는 jQuery 플러그인으로, 사용자가 테이블의 열을 클릭하여 오름차순이나 내림차순으로 정렬할 수 있는 기능을 제공합니다. 이를 통해 데이터를 쉽게 정렬하고 필요한 정보를 빠르게 찾을 수 있습니다.
TableSorter 기본 설정
TableSorter를 사용하려면 먼저 jQuery를 웹 페이지에 추가해야 합니다. 다음으로 TableSorter 라이브러리를 포함하고, HTML 테이블에 적용할 스크립트를 작성해야 합니다. 아래는 기본적인 설정 예제입니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TableSorter Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.34.5/js/jquery.tablesorter.min.js"></script>
<script>
$(document).ready(function(){
$("#myTable").tablesorter();
});
</script>
</head>
<body>
<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>이름</th>
<th>나이</th>
<th>이메일</th>
</tr>
</thead>
<tbody>
<tr>
<td>홍길동</td>
<td>30</td>
<td>hong@gmail.com</td>
</tr>
<tr>
<td>김철수</td>
<td>25</td>
<td>kim@gmail.com</td>
</tr>
<tr>
<td>이영희</td>
<td>28</td>
<td>lee@gmail.com</td>
</tr>
</tbody>
</table>
</body>
</html>
위 예제에서는 먼저 jQuery 라이브러리를 추가하고, TableSorter 라이브러리를 포함시켰습니다. 그리고 document.ready 함수 내에서 $("#myTable").tablesorter()
를 호출하여 myTable
이라는 ID를 가진 테이블에 TableSorter를 적용했습니다.
정렬 가능한 열 지정하기
기본적으로 TableSorter는 모든 열을 정렬 가능하게 설정합니다. 그러나 특정 열만 정렬 가능하도록 지정할 수도 있습니다. 예를 들어, 세 번째 열인 ‘이메일’ 열만 정렬 가능하도록 설정하려면 다음과 같이 코드를 수정합니다.
<thead>
<tr>
<th>이름</th>
<th>나이</th>
<th data-sorter="false">이메일</th>
</tr>
</thead>
위 코드에서는 이메일 열의 data-sorter
속성을 false
로 설정하여 정렬 기능을 비활성화했습니다. 따라서 사용자는 이 열을 클릭해도 정렬이 되지 않습니다.
필수 CSS 추가하기
테이블에 TableSorter를 적용할 때, TableSorter 테마와 일치하는 스타일을 적용해야 합니다. TableSorter는 theme.default.css
와 같은 테마 스타일 시트를 제공하므로, 이를 포함하여 적절한 스타일을 적용할 수 있습니다.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.34.5/css/theme.default.min.css">
이렇게 함으로써 테이블에 TableSorter를 적용할 때 테마 스타일이 적용되어 보다 멋진 외관을 가질 수 있습니다.
이제 여러분도 TableSorter를 사용하여 웹 페이지에 보기 좋은 데이터 그리드를 만들어 볼 수 있습니다. 간단한 설정만으로도 데이터를 간편하게 정렬하고 필터링할 수 있는 강력한 기능을 제공합니다.
더 많은 TableSorter 기능과 옵션에 대해서는 TableSorter 공식 문서를 참고하시기 바랍니다.