[코딩애플 cha.03] Javascript_function 문법 사용법

R_jin·2023년 6월 28일
1

Javascript

목록 보기
3/12
post-thumbnail

function?

:함수(function)란 하나의 특별한 목적의 작업을 수행하도록 설계된 독립적인 블록을 의미하며,
function은 재사용이 용이하여 필요할 때마다 호출하여 해당 작업을 반복해서 수행할 수 있다.

- function 문법

  1. 함수의 이름
  2. 괄호 안에 쉼표(,)로 구분되는 함수의 매개변수(parameter)
  3. 중괄호({})로 둘러싸인 자바스크립트 실행문

- Code

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
      .alert-box {display:none;padding:20px;color:#FFF;border-radius:5px;background-color:#000;}
    </style>
</head>
<body>
    <div id="alert-box" class="alert-box">
        알림창이다.
        <button onclick="document.getElementById('alert-box').style.display='none';">닫기</button>
    </div>
    <button onclick="alet()">버튼이다</button>
    
    <script>
        //function 작명()하여 사용
        function alet(){
            document.getElementById("alert-box").style.display = "block";
        }
        
    </script>
</body>
</html>

function 작명방법

  1. 소문자로 시작(띄어쓰기,언더바는 사용안함)
  2. camelCase
    [옳은예시] openAlert()
    [틀린예시] open_alert()

*camelCase 표기법

  • 첫 글자를 대문자로 적되, 맨 앞에 오는 글자는 소문자로 표기.
  • 표기한 모습이 낙타의 등과 같다고 하여 카멜 표기법이라고 함.

Javascript의 사용법

  1. 자바스크립트의 경우, 작업할 HTML의 하단에 코드를 작업해야 반영이 잘된다.
  2. selecter 오타주의(개발자 도구에서 디버깅을 이용해 에러찾기)
  3. 기본문법 오타

[오늘의 과제]

'닫기'버튼부분의 코드를 함수로 축약해보기

- 과제 code

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="alert-box" class="alert-box">
        알림창이다.
        <button onclick="closeBtn()">닫기</button>
    </div>
    <button onclick="alet()">버튼이다</button>
    
    <script>
        //function 작명()하여 사용
        function alet(){
            document.getElementById("alert-box").style.display = "block";
        }
        
        function closeBtn(){
            document.getElementById('alert-box').style.display='none';
        }
        
    </script>
</body>
</html>
profile
3년차 퍼블리셔의 스터디

0개의 댓글