본문 바로가기

프로그래밍/자바스크립트

[자바스크립트]이벤트 : 이벤트 처리 방법

1. 인라인 방식

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인라인 이벤트 처리</title>
</head>
<body>
    <input type="button" value="이동" onclick="location.href='https://www.naver.com';">    <!-- 한줄만 작성시 세미콜론 생략 가능 -->
    <input type="button" value="확인" onclick="alert('클릭');alert('click');">     <!-- 두줄이상 작성시 세미콜론 필수 -->
 
</body>
</html>
cs

 

2. 함수 이용 방식

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인라인 이벤트 처리 - 함수 이용</title>
<style type="text/css">
div{
        background-color:orange;
    }
</style>
<script type="text/javascript">
    function whenClick(){
        alert('CLICK');
    }
</script>
</head>
<body>
    <div id ="header" onclick="whenClick();">클릭</div>
</body>
</html>
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>이벤트 처리</title>
<script type="text/javascript">
    function changeColor(color){
        document.body.style.backgroundColor = color;
    }
</script>
</head>
<body>
    <form>
        <input type="radio" name="color" value="blue" onclick="changeColor('lightblue')">파랑색
        <input type="radio" name="color" value="green" onclick="changeColor('lightgreen')">녹색
        <input type="radio" name="color" value="white" onclick="changeColor('white')">흰색
    </form>
 
</body>
</html>
cs