본문 바로가기
JS

221229 JS 기본 이벤트 모델

기본 이벤트 모델
HTML요소를 취득 후 이벤트를 익명함수로 연결하는 방식. 선호됨.

HTML요소를 취득할 때는 순서상
"취득할 요소"가
"요소 취득 명령어" 이전에 있어야 함.
태그를 script로 끌고 와서 js에서 이벤트를 심어주는 것.
=>스크립트코드가 태그보다 밑에 있어야 한다!

ex)

<button id="bt">인라인이벤트</button>

<script>
	var bt=document.getElementById("bt");
	bt.onclick=function(){
		console.log("출력");
	}
</script>


스크립트가 위에 있으면 getElementById()안의 id가 없다(null).
null.onclick은 에러.

 

 

<!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>Document</title>
</head>

<body>

    <button id="btn">기본이벤트</button>

    <script>
        var a = document.getElementById("btn");
        //console.log(a);//a는 태그임
        a.onclick = function () {
            console.log('기본이벤트');
            console.log(this);//태그. 자기 자신. 
            console.log(a);//태그. 자기 자신. 
        }

    </script>


</body>

</html>



 



스크립트가 위에 써져야 할 때가 있다.
->window.onload : 화면로딩이 끝난 이후에 실행한다.
로 문제 해결.
단, onload는 화면별로 1개만 사용할 수 있다.

<!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>Document</title>
</head>

<body>

    <script>
        //화면 로딩이 완료된 이후에 실행-onload는 화면별로 1개만 사용할 수 있습니다.
        window.onload = function () {

            var a = document.getElementById("btn");
            a.onclick = function() {
                console.log('기본이벤트');
            }
        }

    </script>



    <button id="btn">기본이벤트</button>
</body>

</html>

'JS' 카테고리의 다른 글

221229 JS this  (0) 2022.12.29
221229 JS 표준 이벤트 모델  (0) 2022.12.29
221229 JS 인라인 이벤트 모델  (0) 2022.12.29
221229 JS 이벤트핸들러  (0) 2022.12.29
221229 JS JSON함수  (0) 2022.12.29