Javascript:표 정렬

학교의 모든 지식. SMwiki
둘러보기로 이동 검색으로 이동

틀:Javascript

  1. Javascript:개요
  2. Javascript:변수, 상수
    1. Javascript:자료구조
  3. Javascript:연산자
  4. 분기문
    1. Javascript:조건문
    2. Javascript:반복문
  5. Javascript:선택자
    1. Javascript:요소 내용 변경
    2. Javascript:HTML로부터 데이터 받기
  6. Javascript:이벤트
    1. Javascript:클릭 이벤트
  7. Javascript:AJAX
    1. AJAX 활용
      1. Javascript:댓글달기
      2. Javascript:무한 스크롤링
  8. Javascript:활용
    1. Javascript:표 정렬

개요[편집 | 원본 편집]

표의 내용에 따라 오름차순, 내림차순의 정렬.

정렬 스크립트[편집 | 원본 편집]

https://www.w3schools.com/howto/howto_js_sort_table.asp의 코드를 참고하였다.

취향에 따라 구현 방법은 다르겠지만.. 테이블 태그 안에서 함수를 호출하여 사용하자.

<table class="table table-hover sortable" id="jb-table">
    <thead class="table-dark">
    <tr>
        <th onclick="sortTable(0)">문항</th>
        <th onclick="sortTable_int(1)">점수</th>

일반 텍스트[편집 | 원본 편집]

<script>
function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("jb-table");
  switching = true;
  // Set the sorting direction to ascending:
  dir = "asc";
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /* Loop through all table rows (except the
    first, which contains table headers): */
    // i값으로 몇행부터 정렬 할지 정한다.
    for (i = 3; i < (rows.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Get the two elements you want to compare,
      one from current row and one from the next: */
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /* Check if the two rows should switch place,
      based on the direction, asc or desc: */
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark that a switch has been done: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      // Each time a switch is done, increase this count by 1:
      switchcount ++;
    } else {
      /* If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again. */
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
</script>

숫자[편집 | 원본 편집]

11, 5 등의 숫자데이터는 자바스크립트에서 자료형을 바꿔주지 않으면 텍스트로 처리하여 정렬해 오름차순에서 11보다 5가 큰 것으로 인식한다.

<script>
function sortTable_int(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("jb-table");
  switching = true;
  // Set the sorting direction to ascending:
  dir = "asc";
  /* Make a loop that will continue until
  no switching has been done: */
  while (switching) {
    // Start by saying: no switching is done:
    switching = false;
    rows = table.rows;
    /* Loop through all table rows (except the
    first, which contains table headers): */
    // i값으로 몇행부터 할지 정한다.
    for (i = 3; i < (rows.length - 1); i++) {
      // Start by saying there should be no switching:
      shouldSwitch = false;
      /* Get the two elements you want to compare,
      one from current row and one from the next: */
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      x = parseInt(x.innerHTML)
      y = parseInt(y.innerHTML)
        /* Check if the two rows should switch place,
      based on the direction, asc or desc: */
      if (dir == "asc") {
        if (x > y) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (x < y) {
          // If so, mark as a switch and break the loop:
          shouldSwitch = true;
          break;
        }
      }
    }
    // 행을 바꾸는 동작.
    if (shouldSwitch) {
      /* If a switch has been marked, make the switch
      and mark that a switch has been done: */
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      // Each time a switch is done, increase this count by 1:
      switchcount ++;
    } else {
      /* If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again. */
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
</script>