728x90
<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>
let add = function (fir, sec) { // 함수 생성
let result = fir + sec;
return result;
};
alert(add(23, 42));
</script>
</body>
</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>
let obj = {
name: "KMG",
studentNum: 12201863,
getStudentNum: function () {
return this.studentNum;
},
};
alert(obj.getStudentNum());
</script>
</body>
</html>
DOM(Document Object Model)
: HTML의 요소들을 자바스크립트로 접근하고 수정할 수 있도록 한다.
1) DOM을 이용해 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>
let dom = document.getElementById("hi");
document.writeln(dom.textContent);
</script>
</body>
</html>
2) DOM을 이용헤 HTML의 태그 가져오기
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id = "heading">Hi H I</h1>
<script>
let head = document.getElementById("heading");
head.textContent = "Hello, World";
</script>
</body>
</html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="hi">Hello</h1>
<script>
let dom = document.getElementById("hi");
document.writeln(dom.textContent);
</script>
</body>
</html>
element.textContent = "내용"
: head의 값을 가져와 출력하는 역할
<이벤트 핸들러>
<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>
<input type = "button" value = "alert" onclick = "alert('Hello ,world')"; />
</body>
</html>
728x90