이벤트 다루기 (onblur -> addeventListener)

KHW·2020년 11월 30일
0

Javascript 지식쌓기

목록 보기
2/95

1) 기본코드 onblur 사용

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onfocus와 onblur</title>
<script>
function checkFilled(obj) {
	if(obj.value == "") {
		alert("enter name!");
		obj.focus(); // obj에 다시 포커스
	}
}
</script>
</head>
<body onload=
	"document.getElementById('name').focus();">
<h3>onfocus와 onblur</h3>
<hr>
<p>이름을 입력하지 않고 다른 창으로
이동할 수 없습니다.</p>
<form>
이름 <input type="text" id="name"
			onblur="checkFilled(this)"><p>
학번 <input type="text">
</form>
</body>
</html>

2) addEventListener('blur',function) 사용

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>onfocus와 onblur</title>

</head>
<body onload=
	"document.getElementById('name').focus();">
<h3>onfocus와 onblur</h3>
<hr>
<p>이름을 입력하지 않고 다른 창으로
이동할 수 없습니다.</p>
<form>
이름 <input type="text" id="name"><p>
학번 <input type="text">
</form>
    <script>
       let name= document.querySelector('#name');
        name.addEventListener('blur',function checkFilled() {
	if(this.value == "") {
		alert("enter name!");
		this.focus(); // obj에 다시 포커스
	}
})

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

중요 포인트

1) onblur를 통한 함수(this)의 this는

<input type="text" id="name" onblur="checkFilled(this)">

이것을 나타낸다.

2) addEventListener에서의 this도 또한

<input type="text" id="name" onblur="checkFilled(this)">

이것을 나타낸다.

3) 즉 1)의경우 매개변수로 받은 this인 obj를 통해 obj.focus()를 실행하는 것이고 2)의경우 Dom객체 name을 통해 받은 this 자체를 나타내야하므로 this.focus()를 해야한다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글

관련 채용 정보