프론트엔드 개발 시 발생하는 주요 문제 해결 기술

1. 속성 기반 요소 선택

특정 속성 값을 기반으로 DOM 요소를 선택하는 방법입니다.

// jQuery 사용
$('input[data-type="user-category"]');

// 원생 JavaScript 사용
document.querySelectorAll('input[data-type="user-category"]');

2. 동적 생성 요소 이벤트 처리

페이지 로딩 후 동적으로 생성된 요소에 이벤트를 바인딩할 때는 document 레벨에서 처리해야 합니다.

// jQuery 사용
$(document).on('click', 'input[data-role="checkbox"].custom-class', function() {
  // 처리 로직
});

// 직접 HTML에 onclick 속성 추가
<div onclick="handleClick(this, userId, value)"></div>

3. 테이블 tbody에 스크롤바 적용

테이블의 tbody 영역에 고정된 높이와 스크롤바를 설정하는 방법입니다.

.scrollable-tbody {
  max-height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}

.table-header {
  display: table;
  width: 100%;
  table-layout: fixed;
}

.table-row {
  display: table;
  width: 100%;
  table-layout: fixed;
}

4. 외부 JS 파일 동적 로딩

실행 중에 외부 JavaScript 파일을 동적으로 로드하는 방법입니다.

const script = document.createElement('script');
script.src = '/assets/js/config.js';
document.head.appendChild(script);

// 또는 jQuery를 사용한 방법
$.getScript('/path/to/script.js');

5. 체크박스 반복 처리

체크된 항목을 반복하며 처리하는 방법입니다.

// 일반 반복
$('input:checked').each(function() {
  console.log($(this).val());
});

// 특정 클래스를 가진 체크박스 반복
$('.selected-items:checked').each(function() {
  console.log($(this).val());
});

// 체크된 항목의 속성 값 가져오기
function processSelectedItems() {
  $('.selected-items').each(function() {
    if ($(this).prop('checked')) {
      const value = $(this).attr('data-value');
      if (value) {
        // 처리 로직
      }
    }
  });
}

// 체크된 항목의 ID를 배열로 저장
function collectSelectedIds() {
  const ids = [];
  $('.selected-items').each(function() {
    if ($(this).prop('checked')) {
      ids.push($(this).attr('data-id'));
    }
  });
  return ids;
}

6. 전체 선택 및 개별 선택 관리

체크박스의 전체 선택 및 개별 선택을 관리하는 방법입니다.

<table>
  <thead>
    <tr>
      <th id="select-all-th">
        <input type="checkbox" id="select-all" name="select-all"/>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <input type="checkbox" data-id="1" class="select-item"/>
      </td>
    </tr>
  </tbody>
</table>

<script>
$(function() {
  function initCheckbox() {
    const $selectAll = $('#select-all');
    const $items = $('.select-item');

    $selectAll.click(function(event) {
      $items.prop('checked', $(this).prop('checked'));
      if ($(this).prop('checked')) {
        $items.closest('tr').addClass('highlight');
      } else {
        $items.closest('tr').removeClass('highlight');
      }
      event.stopPropagation();
    });

    $items.click(function(event) {
      $(this).closest('tr').toggleClass('highlight');
      $selectAll.prop('checked', $items.filter(':checked').length === $items.length);
      event.stopPropagation();
    });
  }
  initCheckbox();
});
</script>

7. 우상단 알림 표시

우상단에 작은 알림 표시를 추가하는 방법입니다.

<li role="presentation" class="text-center" id="notification-item"
    style="width: 16%; font-weight: bold; font-size: 15px">
  <a href="javascript:void(0)" id="notification-link"
     onclick="handleNotification(this, '6')">
    진행 중 <span id="count-notification"></span>
    <span id="notification-badge" class="notification-badge"></span>
  </a>
</li>

<style>
.notification-badge {
  color: red;
  position: absolute;
  top: 9px;
  right: 10px;
  text-align: center;
  font-size: 9px;
  padding: 2px 3px;
  line-height: .9;
}
</style>

8. 텍스트 초과 시 생략 표시

텍스트가 지정된 너비를 초과할 경우 생략 기호를 표시하는 방법입니다.

.text-ellipsis {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 85%;
}

9. 요소에 스크롤바 설정

요소에 수직 또는 수평 스크롤바를 설정하는 방법입니다.

<ul class="custom-dropdown" style="max-height: 80px; overflow-y: auto; overflow-x: hidden">
  <li><a href="javascript:void(0)" onclick="handleOption(this, '1')">옵션1</a></li>
  <li><a href="javascript:void(0)" onclick="handleOption(this, '2')">옵션2</a></li>
</ul>

10. 스크롤바 스타일링

Webkit 기반 브라우저에서 스크롤바 스타일을 맞춤화하는 방법입니다.

.custom-scrollbar {
  height: 540px;
  overflow-y: auto;
  overflow-x: hidden;
}

.custom-scrollbar::-webkit-scrollbar {
  width: 5px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: #8c85e6;
}

11. input 요소 마지막 위치 포커스

input 요소의 텍스트 마지막 위치에 포커스를 설정하는 방법입니다.

const inputElement = document.querySelector('input');
const value = inputElement.value;
inputElement.value = '';
inputElement.focus();
inputElement.value = value;

// 또는
inputElement.setSelectionRange(value.length, value.length);

12. input 요소 blur 이벤트 처리

input 요소의 blur 이벤트를 처리할 때, 다른 요소 클릭 시 발생하는 이벤트를 조절하는 방법입니다.

// blur 이벤트 대신 onmousedown을 사용하여 클릭 시점에 처리
<div onmousedown="preventBlur()"></div>

function preventBlur() {
  // 처리 로직
}

13. 모달 창 데이터 로딩 문제 해결

모달 창에 동적 데이터를 로딩할 때 표시되지 않는 문제 해결 방법입니다.

const modal = document.getElementById('modal-content');
modal.style.display = 'block';
modal.querySelector('.content').innerHTML = '<div>데이터</div>';

14. 시간 형식 변환

날짜와 시간을 원하는 형식으로 변환하는 방법입니다.

function formatDate(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

15. 현재 시간 가져오기 및 포맷팅

현재 시간을 특정 형식으로 가져오는 방법입니다.

function getCurrentFormattedDate(daysToAdd = 0) {
  const now = new Date();
  now.setDate(now.getDate() + daysToAdd);
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

16. 특정 이벤트 트리거

요소에 이벤트를 프로그래밍적으로 트리거하는 방법입니다.

// jQuery 사용
$('#data-batch').val('2').trigger('change');

// 원생 JavaScript 사용
const element = document.getElementById('data-batch');
element.value = '2';
element.dispatchEvent(new Event('change', { bubbles: true }));

17. 빈 객체 확인

객체가 비어 있는지 확인하는 방법입니다.

// 방법 1
Object.keys(data).length === 0

// 방법 2
JSON.stringify(data) === '{}'

18. 특정 월의 일 수 계산

특정 연도와 월의 일 수를 계산하는 방법입니다.

function getDaysInMonth(year, month) {
  return new Date(year, month, 0).getDate();
}

19. 타이머 설정

특정 시간 후 함수를 실행하는 방법입니다.

function delayedSearch() {
  // 처리 로직
}

setTimeout(delayedSearch, 1200);

20. 주기적 실행

일정 간격으로 함수를 반복 실행하는 방법입니다.

setInterval(checkUnreadMessages, 15000);

21. 간결한 조건문

삼항 연산자를 사용한 간결한 조건문 작성 방법입니다.

const status = 'F';
const disabled = status === 'F' ? '' : 'disabled';

// 또는
const result = `${status === 'F' ? '' : 'disabled'}`;

22. 요소 숨기기

요소를 숨기는 두 가지 방법입니다.

// visibility 속성 사용
element.style.visibility = 'hidden'; // 공간을 차지함

// display 속성 사용
element.style.display = 'none'; // 공간을 차지하지 않음

23. 특정 순서의 요소 찾기

특정 위치의 요소를 선택하는 방법입니다.

// 첫 번째 tr의 5번째 td 선택
$('.container').find('tr').eq(4).find('td');

// nth-child를 사용한 방법
$('.container tr:nth-child(5) td');

태그: jQuery CSS JavaScript DOM Web Development

8월 15일 00:05에 게시됨