본문 바로가기
: ) Web/웹 스터디

[JS] [이론] function 문법

by miiinn 2024. 1. 5.

function 문법

▸긴 코드를 짧은 단어로 축약

⌨️ <script> function 작명() {축약할코드} </scrpt>

 

<script>
    function openAlert(){
        document.getElementById('box').style.display = 'block';
    }
</script>

 

▸ function문법 작명 규칙

1. 소문자 시작

2. camelCase


 

 

📌 주의 사항

  1. 조작할 HTML 하단에 코드를 짜야 잘된다.
  2. 셀렉터 오타 주의 (id찾을 때 주의)
  3. 그냥 기본 문법 오타

→ 크롬디버깅 이용


 

🔎 알림창 닫기 버튼 funtion문법으로 축약하기

 

[HTML]

<div id="box" class="alert-box">Alert!
    <button onclick="closeAlert()">닫기</button>
</div>
    <button onclick="openAlert()">버튼</button>

<script>
    function openAlert(){
        document.getElementById('box').style.display = 'block';
    }

    function closeAlert(){
        document.getElementById('box').style.display = 'none';
    }
</script>

 


▶ function의 파라미터

▸파라미터 예시 1.

⌨️ <script> function 작명(파라미터) {축약할코드} </scrpt>

 

<div id="box" class="alert-box">Alert!
            <button onclick="alert('none')">닫기</button>
</div>
    <button onclick="alert('block')">버튼</button>

<script>
    function alert(any){
        document.getElementById('box').style.display = any;
    }
</script>

 

[HTML]

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" href="main.css">
    </head>
    <body>

        <div id="box" class="alert-box">Alert!
            <button onclick="alert('none')">닫기</button>
        </div>
        <button onclick="alert('block')">버튼</button>

        <script>
            /*function openAlert(){
                document.getElementById('box').style.display = 'block';
            }

            function closeAlert(){
                document.getElementById('box').style.display = 'none';
            }*/
            function alert(any){
                document.getElementById('box').style.display = any;
            }
        </script>

    </body>
</html>

 

▸파라미터 예시 2.

<script>
    function plus(***num***){
        ***2+num***
    }
    plus(1);
    plus(2);
</script>

 

▸파라미터는 여러개 가능하다.


 

📌 id로 찾기

⌨️ getElementById(’id’)

 

📌 class로 찾기

⌨️ getElementByClassName(’class name’)[0]

- [0]은 찾은 것 중에 몇번째 요소를 고를건지

 

📌 태그 안 텍스트 변경하기

⌨️ innerHTML