학원/강의
*54일차 (Javascript)
pringspring
2022. 4. 13. 17:47
@자료형(datatype)
<body>
<h1>자료형</h1>
<button onclick="test1();">test1</button>
<script>
/**
* 자료형
*/
function test1(){
// 변수 선언 키워드 let(변수) / const(상수)
let a; // 자료형이 아직 지정되지 않음
console.log(typeof a, a); // undefined undefined
// 값대입 : 값을 통해 자료형 지정 Dynamic Typing
a = true;
console.log(typeof a, a);
// 자료형
// string 문자열 '' ""
const str = 'abc';
console.log(typeof str, str); // string abc
// number
// 정수/실수 구분하지 않는다.
const num = 123;
console.log(typeof num, num); // number 123
// boolean
const bool = false;
console.log(typeof bool, bool); // boolean false
// object
const obj = {
name : '홍길동',
n : 123.456,
married : true,
hobby : ['축구', '농구'],
foo : function(){
console.log('obj.fooooooooooooooooooooo');
},
friend : {
name : '고길동'
}
};
console.log(typeof obj, obj);
console.log(obj.hobby);
console.log(obj.foo);
console.log(obj.friend);
const today = new Date();
console.log(typeof today, today); // object Wed Apr 13 2022 10:46:31 GMT+0900 (한국 표준시)
const arr = [1, 2, 3];
console.log(typeof arr, arr);
console.log(arr[0], arr[1], arr[2]);
// function
function foo(){
console.log('fooooooooooooooooooooooooooooooooooo');
}
console.log(typeof foo, foo);
foo(); // 함수 호출
// undefined
let h;
console.log(typeof h, h); // undefined undefined
let m = 123;
m = undefined;
console.log(typeof m, m); // undefined undefined
}
</script>
</body>
@access DOM
*DOM
- Document Object Model
- html의 모든요소는 document객체 하위에서 계층구조로 관리됨
- console.dir(document); //children 속성확인
ex) getElementById
- 해당 id를 가진 tag객체 반환
- 존재하지 않는 경우 null 반환
function test1(){
const hw1 = document.getElementById('hw1');
console.log(typeof hw1, hw1);
console.dir(hw1);
console.log('id : ', hw1.id);
console.log('class : ', hw1.className);
console.log('title : ', hw1.title);
console.log('innerHTML : ', hw1.innerHTML);
const notExist = document.getElementById("dskfdlkaskdal");
console.log(typeof notExist, notExist); // object null
// 타입은 object인데, 값이 없는 경우 null
console.log(notExist.id); // Uncaught TypeError: Cannot read properties of null (reading 'id')
//오류남
console.log(12345);
}
ex) getElementByTagName
- 해당 태그객체를 포함하는 배열(가짜)를 반환
function test2(){
const list = document.getElementsByTagName("li");
console.log(typeof list, list);
for(let i = 0; i < list.length; i++){
const li = list[i];
console.dir(li);
console.log(li.id, li.className, li.innerHTML);
li.style.backgroundColor = 'hotpink';
li.style.color = 'white';
li.style.fontSize = '32px';
}
}
ex) getElementByClassName
- 해당 클래스를 가진 태그객체를 배열(가짜)로 변환
function test3(){
const group1 = document.getElementsByClassName("group1");
console.log(typeof group1, group1);
for(let i = 0; i < group1.length; i++){
const li = group1[i];
li.style.textDecoration = 'underline';
}
}
ex) getElementByName
function test4(){
const fruits = document.getElementsByName('fruit');
console.log(typeof fruits, fruits);
let str = "";
for(let i = 0; i < fruits.length; i++){
const fruit = fruits[i];
// console.dir(fruit);
// console.log("%s : %s", fruit.id, fruit.checked); // getter로써 사용
// fruit.checked = true; // setter로써 사용
if(fruit.checked){
str += fruit.value + " ";
}
}
alert(str);
}
ex)실습문제
- input#username[name=username]의 사용자입력값을 alert로 출력
function test5(){
// const username = document.getElementsByName('username')[0];
const username = document.getElementById('username');
// console.log(username);
alert(username.value);
}
ex) input#point input이벤트 핸들러(리스너)
- A : 사용자값 값입력 (핸들조정)
- B : span#pointView 값표시(test6함수)
function test6(){
// const point = document.getElementById('point');
const pointVal = point.value;
console.log(pointVal);
// const pointView = document.getElementById('pointView');
pointView.innerHTML = pointVal;
}
ex) querySelector
- css선택자를 통해 DOM요소를 접근할 수 있다
- 선택자와 일치하는 하나의 요소 반환
- 복수개에 해당하는 선택자여도 첫 요소만 반환
function test7(){
// const elem = document.querySelector('#username');
const elem = document.querySelector('[name=fruit]');
console.log(typeof elem, elem);
console.dir(elem);
}
ex) querySelectorAll
- css 선택자를 통해 DOM요소를 접근할 수 있다
- 선택자와 일치하는 모든 요소 유사배열에 반환
function test8(){
// const elems = document.querySelectorAll('[name=fruit]');
const elems = document.querySelectorAll('ul li');
console.log(typeof elems, elems);
for(let i = 0; i < elems.length; i++){
console.log("%s : %s", elems[i].id, elems[i].checked);
}
}
@className_classList
*클래스값으로 DOM제어
<!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>클래스값으로 DOM 제어</title>
<style>
table {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
text-align: center;
padding: 5px;
}
.on {
background-color: hotpink;
color: #fff;
}
.gungseo {
font-family : 궁서, 'serif';
}
</style>
</head>
<body>
<h1>클래스값으로 DOM 제어</h1>
<!-- table>thead>tr>th -->
<table>
<thead>
<tr>
<th colspan="5">수강신청</th>
</tr>
</thead>
<!-- tbody>tr>td -->
<tbody>
<tr>
<td colspan="5">
<input type="checkbox" id="checkAll" onchange="checkAllChanged()">
<label for="checkAll">전체선택/해제</label>
</td>
</tr>
<!-- tr>(td>input:checkbox[name=subject]#subject$+label[for=subject$])*5 -->
<tr>
<td class="gungseo"><input type="checkbox" name="subject" id="subject1" onchange="subjectChanged(this);"><label for="subject1">국어</label></td>
<td class="gungseo"><input type="checkbox" name="subject" id="subject2" onchange="subjectChanged(this);"><label for="subject2">영어</label></td>
<td class="gungseo"><input type="checkbox" name="subject" id="subject3" onchange="subjectChanged(this);"><label for="subject3">수학</label></td>
<td class="gungseo"><input type="checkbox" name="subject" id="subject4" onchange="subjectChanged(this);"><label for="subject4">사회</label></td>
<td class="gungseo"><input type="checkbox" name="subject" id="subject5" onchange="subjectChanged(this);"><label for="subject5">과학</label></td>
</tr>
</tbody>
</table>
<script>
/**
* [name=subject]가 체크/체크해제되었을때 change이벤트핸들러
* - 어느 체크박스에서 호출한 것인지 확인하기 위해 id매개변수가 꼭 필요
* - this용법1. inline 이벤트속성에 기술된 this는 태그객체 자신이다.
*/
function subjectChanged(subject){
// console.log("this", subject);
toggleClassOn(subject);
// 전체선택 체크박스 처리
// - 모두 체크된 경우 #checkAll.checked = true
// - 하나라도 체크해제된 경우 #checkAll.checked = false
const subjects = document.querySelectorAll('[name=subject]');
const checkedSubjects = document.querySelectorAll('[name=subject]:checked');
const checkAll = document.querySelector("#checkAll");
console.log(subjects, checkedSubjects);
checkAll.checked = (subjects.length == checkedSubjects.length);
}
function toggleClassOn(subject){
const parentTd = subject.parentElement;
if(subject.checked)
parentTd.classList.add("on");
else
parentTd.classList.remove("on");
}
/**
* #checkAll 체크/체크해제했을때 change이벤트핸들러
*/
function checkAllChanged(){
// console.log("checkAllChanged");
// const subjects = document.getElementsByName('subject');
const subjects = document.querySelectorAll('[name=subject]');
// console.log(subjects);
const checkAll = document.querySelector("#checkAll");
for(let i = 0; i < subjects.length; i++){
const subject = subjects[i];
// 1. 체크/체크해제 처리
subject.checked = checkAll.checked;
// 2. 부모td.on 처리
toggleClassOn(subject);
}
}
</script>
</body>
</html>