클릭 이벤트 / this 키워드
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>event</title>
</head>
<style>
h1 {
border: 1px solid #999;
}
</style>
<script>
window.onload = function(){
// 캐스팅_변수선언
var hearder = document.getElementById('header');
// 클릭하면 Click hearder :)♡가 뜨는 onclick 이벤트 연결
header.onclick = function(){
alert('Click header :)♡ '+this.innerHTML);
// this > 이벤트가 발생한 header를 가리키고 있다
// 여기서 this.innerHTML는 C L I C K! 이다
// 이벤트 제거 > 한번 클릭하고 나면 창이 다시뜨지 않는다.
header.onclick = null;
}
};
</script>
<body>
<h1 id="header"> C L I C K ! </h1>
</body></html>
이벤트 강제실행
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>event</title>
</head>
<style>
h1 {
border: 1px solid #999;
}
</style>
<script>
window.onload = function(){
// 캐스팅
var btn1 = document.getElementById('btn1'); //버튼id
var btn2 = document.getElementById('btn2');
var cnt1 = document.getElementById('count-a');
var cnt2 = document.getElementById('count-b');
// btn 문서객체에 클릭이벤트 적용
btn1.onclick = function(){
// 클릭하면 숫자증가
cnt1.innerHTML = Number(cnt1.innerHTML)+1;
// a를 누르면 b 버튼 카운트도 같이 증가하고 싶다면
//btn2.onclick();
};
btn2.onclick = function(){ //inner나 text나 둘다상관없음
cnt2.innerHTML = Number(cnt2.textContent)+1;
};
};
</script>
<body>
<button id="btn1">Button-A</button>
<button id="btn2">Button-B</button>
<h1>Button-A : <span id="count-a">0</span></h1>
<h1>Button-B : <span id="count-b">0</span></h1>
</body></html>
인라인 이벤트 모델
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>event</title>
</head>
<style>
h1 {
border: 1px solid #999;
}
</style>
<script>
function clickH1(){
alert('인라인 방식으로 이벤트 처리');
}
</script>
<body>
<h1 onclick="clickH1();">인라인 방식의 이벤트 정의</h1>
</body></html>
'front-end > Javascript & jquery' 카테고리의 다른 글
[자바스크립트 ] 이벤트 삭제 (0) | 2020.11.30 |
---|---|
[자바스크립트] 이벤트 전달 / 막기 (bubbling) / stopPropagation (0) | 2020.11.30 |
[자바스크립트] 유효성검사 (0) | 2020.11.30 |
[자바스크립트] 문서객체의 스타일 조작 (0) | 2020.11.30 |
[자바스크립트] 문서 객체 가져오기 / getElementById / querySelector (0) | 2020.11.30 |
[자바스크립트] 문서객체 만들기 / createElement / createTextNode (0) | 2020.11.30 |
[자바스크립트] onload (0) | 2020.11.30 |