WEB

[HTML/JavaScript] 효율적인 event처리 example

yo~og 2021. 10. 8. 18:13
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Step02_example.html</title>
</head>
<body>
    <input type="text" id="inputMsg" placeholder="메세지 입력...">
    <button id="sendBtn">전송</button>
    <p id="result"></p>
    <script>
        /*
            위의 input 요소에 문자열을 입력하고
            전송 버튼을 누르면
            input요소에 입력한 문자열이
            p요소의 innerText로 출력이 되도록 프로그래밍 해보세요.
        */

        document.querySelector("#sendBtn").addEventListener("click",function(){
            let msg = document.querySelector("#inputMsg").value;
            document.querySelector("#result").innerText = msg;
        });

    </script>
</body>
</html>

input 요소에 문자열을 입력하고 전송버튼을 누르면 input요소에 입력한 문자열이 p요소에 출력되도록 프로그래밍 하는 예제이다.

document.querySelector("#sendBtn")해서 버튼을 찾아준 후 addEventListener을 사용한다.

클릴할 때 실행되야하므로 클릭이벤트이다.

결과적으로,

document.querySelector("#sendBtn").addEventListener("click",function(){
           
        });

이렇게 만들어주고 function안에 text를 가져오는 코드를 짠다.

input요소에서 text를 추출해야하므로 input요소의 id인 inputMsg를 사용한다. 

document.querySelector("#inputMsg").value를 사용해서 text를 추출한다.

이 text를 p안에 넣어야한다.

document.querySelect("#result").innerText = "값"

값에다가 추출한 text를 넣으면 된다.