Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 경고창(alert) 버튼 레이블을 변경하는 방법

JavaScript 경고창 버튼 레이블 변경하기

JavaScript에서 기본적으로 제공하는 alert() 함수로 생성된 표준 경고창(알림 상자)은 브라우저가 직접 렌더링하기 때문에 버튼의 텍스트를 사용자 마음대로 변경할 수 없습니다. 항상 "확인" 또는 "OK"로 고정되어 있죠.

따라서 버튼 레이블을 자유롭게 바꾸려면 커스텀 경고창(Custom Alert Box)을 만들어야 합니다. 아래 예제에서는 기존 경고창의 "OK" 버튼을 "Thank you for informing!"(소중한 알림 감사합니다!)이라는 문구로 변경한 모습을 확인할 수 있습니다.

커스텀 경고창 구현 예제

jQuery를 활용해 메시지와 버튼 레이블을 동적으로 설정하는 전체 코드입니다.

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
      </script>
      <script>
         function functionAlert(msg, myYes) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #91FF00;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 100px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class = "message">This is a warning message.</div>
         <button class="yes">Thank you for informing!</button>
      </div>
      <input type="button" value="Click Me" onclick="functionAlert();" />
   </body>
</html>

코드 동작 원리

  • functionAlert(msg, myYes): 경고창에 표시할 메시지(msg)와 확인 버튼 클릭 시 실행될 콜백 함수(myYes)를 인자로 받습니다.
  • .message: 전달받은 메시지를 경고창 내부에 동적으로 삽입합니다.
  • .unbind().click(): 버튼에 이미 등록된 이벤트를 초기화한 후 새로운 클릭 이벤트를 연결하여, 여러 번 호출해도 이벤트가 중복 실행되지 않도록 합니다.
  • CSS 스타일링: #confirm 요소를 position: fixed로 화면 중앙에 고정하고, 처음에는 display: none으로 숨겨두었다가 호출 시에만 보여줍니다.

마무리

이처럼 표준 alert() 대신 HTML과 CSS, jQuery를 조합한 커스텀 경고창을 사용하면 버튼 레이블뿐만 아니라 디자인, 위치, 애니메이션까지 완전히 자유롭게 제어할 수 있습니다. 실무에서는 jQuery 없이 순수 JavaScript나 SweetAlert 같은 라이브러리를 활용하는 방법도 널리 사용되니, 프로젝트 상황에 맞게 선택하시면 됩니다.