development/html javascript CSS
[JavaScript] 함수 이용하기
Happyoon ~
2021. 10. 8. 00:47
728x90
반응형
핵심
1. 함수는 특정 시점에 일괄 수행할 javascript를 모아 놓는 역할을 한다.
2. 함수는 페이지 로딩시점에 생성되고 호출을 통해 호출되는 시점에 실행된다.
3. document.querySelector('p').innerText = num1;
4. ' . '이후에 쓰이는 것을 우리는 '참조한다' 라고 말한다.
예제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>
<button onclick = "clicked()">눌러보셈</button>
<script>
console.log("페이지 로딩중 ...");
// 함수는 특정시점에 일괄 수행할 javascript를 모아 놓는 역할을 한다.
function clicked(){
console.log("하나");
console.log("두울");
console.log("셋");
}
</script>
</body>
</html>
예제2
onclick과 함수를 사용하여 클릭(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>
<button onclick="changePhoto()">
눌러보셈
</button>
<br>
<img src="images/kim1.png">
<script>
function changePhoto(){
document.querySelector('img').setAttribute('src','images/kim2.png');
}
</script>
</body>
</html>
예제3
두 개의 버튼에 각각 함수 적용.
<!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>hello3</title>
</head>
<body>
<button onclick="changePhoto1()">눌러보셈</button>
<button onclick="changePhoto2()">눌러보셈2</button>
<br>
<img src="images/kim1.png">
<script>
function changePhoto1(){
document.querySelector('img').setAttribute('src','images/kim2.png');
}
function changePhoto2(){
document.querySelector('img').setAttribute('src','images/kim1.png');
}
</script>
</body>
</html>
예제4
onmouseover을 사용하여 마우스를 올렸을 때 함수가 실행되도록 구현
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=
, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick = "clicked()">눌러보셈</button>
<button onmouseover = "clicked()">마우스를 올리셈</button>
<p>0</p>
<script>
//페이지 로딩시점에 num1이라는 변수를 만들고 0을 대입하기
let num1 = 0;
//페이지 로딩 시점에 clicked라는 이름의 함수 만들기(호출x)
function clicked(){
//버튼을 누를 때
//num1에 있는 값에 1을 더해서 다시 num1에 대입하기
num1 = num1+1;
//p요소의 innerText에 num1에 있는 값을 넣어주기
document.querySelector('p').innerText = num1;
}
</script>
</body>
</html>
반응형