- 기념일 계산 + isNaN 대응
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
|
<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>내장객체 응용</title>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container{
margin: auto auto;
border: 1px solid #ccc;
width: 500px;
text-align: center;
}
.day1{
padding: 10px;
}
.day1>h3{
font-size: 1.2em;
color: #666;
}
.day1 .count{
font-family: "맑은 고딕",sans-serif;
font-weight: bold;
font-size: 3.5em;
margin: 10px 10px 0 10px;
line-height: 90px;
}
.bar{
width: 100%;
margin-top: 60px;
padding-left: 20px;
height: 40px;
background-color: #747474;
color: #fff;
font-size: 1.2em;
line-height: 40px;
}
.day2{
width: 420px;
margin: 20px auto;
}
.day2 ul{
list-style: none;
border-bottom: 1px dashed #ccc;
height: 60px;
}
.day2 ul:last-child{
border-bottom: none;
}
.day2 .item_title{
float: left;
width: 160px;
font-weight: bold;
font-size: 1.5em;
line-height: 60px;
}
.day2 .item_date{
float: left;
margin-left: 80px;
font-size: 1.2em;
text-align: center;
line-height: 60px;
}
</style>
<script>
var now=new Date();
var check=false;
var errString;
var day=prompt("언제 처음 만났나요?","yyyy-mm-dd");
if (day!=null){ //취소 여부 확인
check=true;
} else{
errString="취소했습니다.";
}
if (check){
var firstDay=new Date(day);
if(!isNaN(firstDay)){ //문자 여부 확인
var toNow=now.getTime();
var toFirst=firstDay.getTime();
var passedTime=toNow-toFirst;
var passedDay=Math.round(passedTime/(24*60*60*1000));
//밀리초 -> 일 단위 변환 } else{
check=false;
errString="문자는 입력할 수 없습니다";
}
}
window.onload=function(){
if (check){
document.querySelector("#count").innerHTML=passedDay+"일";
document.querySelector("#title").innerHTML+=" ("+day+")";
calDate(100);
calDate(200);
calDate(365);
calDate(1000);
} else{
document.querySelector('#count').innerHTML="알수없음";
alert(errString);
}
}
function calDate(days){
var future=toFirst+days*(24*60*60*1000); //처음 만난 날 + 100,200일,..
var someday=new Date(future);
var year=someday.getFullYear();
var month=someday.getMonth()+1;
var date=someday.getDate();
document.querySelector('#date'+days).innerHTML=year+
"년 "+month+"월 "+date+"일";
}
</script>
</head>
<body>
<div class="container">
<div class="day1">
<h3 id="title">우리 만난 지</h3>
<p class="count" id="count">며칠?</p>
</div>
<div class="bar">기념일 계산</div>
<div class="day2">
<ul>
<li class="item_title">100일</li>
<li class="item_date" id="date100"></li>
</ul>
<ul>
<li class="item_title">200일</li>
<li class="item_date" id="date200"></li>
</ul>
<ul>
<li class="item_title">1년</li>
<li class="item_date" id="date365"></li>
</ul>
<ul>
<li class="item_title">1000일</li>
<li class="item_date" id="date1000"></li>
</ul>
</div>
</div>
</body>
|
cs |
- 객체 생성 - 생성자 함수 이용
<script>
function Book(title, pages, price, author){
this.title=title;
this.pages=pages;
this.price=price;
this.author=author;
}
var html=new Book('웹표준의 정석',500,28000,'김철수');
var youtube=new Book('유튜브 영상 만들기',300,25000,'이영희');
var python=new Book('파이썬 기본',520,32000,'홍길동');
</script>
- 속성 (cf.자바=> 필드)
<script>
function Book(title, pages, price, author){
this.title=title;
this.pages=pages;
this.price=price;
this.author=author;
}
var html=new Book('웹표준의 정석',500,28000,'김철수');
var youtube=new Book('유튜브 영상 만들기',300,25000,'이영희');
var python=new Book('파이썬 기본',520,32000,'홍길동');
var bookList=[html, youtube, python];
document.write('<h1>신간 도서 목록</h1>');
for(var i=0;i<bookList.length;i++){
document.write('<p>제목 : '+bookList[i].title+'</p>');
document.write('<p>가격 : '+bookList[i].price+'</p>');
document.write('<p>작가 : '+bookList[i].author+'</p><br>');
}
</script>
- 메서드 : 속성이 함수
<script>
//생성자 함수 (속성5, 메서드3)
function Student(name, kor, mat, eng, sci){
//속성 (cf. 자바: 필드)
this.name=name;
this.kor=kor;
this.mat=mat;
this.eng=eng;
this.sci=sci;
//메서드
this.getSum=function(){
return this.kor+this.mat+this.eng+this.sci;
};
this.getAvg=function(){
return this.getSum()/4;
};
this.toString=function(){
return this.name+" "+this.getSum()+" "+this.getAvg();
};
}
//인스턴스 객체 생성 => 편리X
//var student1=new Student('홍길동', 90,70,85,60);
//배열에 객체 생성
var students=[];
students.push(new Student('홍길동',90,70,85,60));
students.push(new Student('김철수',74,80,70,88));
students.push(new Student('이영희',70,55,60,90));
document.write("<h2>** 3학년 1반 성적표 **</h2>");
document.write("이름 총점 평균<br>");
for (var i in students){
document.write(students[i].toString()+"<br>");
}
</script>
- 프로토타입 : 생성자함수로 생성된 객체가 공통으로 가지는 공간
=> 자바스크립트에는 클래스 대신 프로토타입 존재
=> 프로토타입 통해 상속 구현
=> 생성자 함수에 메서드 정의 -> 객체 생성마다 같은 메소드 반복 생성하여 메모리 낭비
=> 프로토타입 객체에 메소드 추가해 메모리 절약
<script>
function Student(name, kor, mat, eng, sci){
this.name=name;
this.kor=kor;
this.mat=mat;
this.eng=eng;
this.sci=sci;
}
//프로토타입
Student.prototype.getSum=function(){
return this.kor+this.mat+this.eng+this.sci;
};
Student.prototype.getAvg=function(){
return this.getSum()/4;
};
Student.prototype.toString=function(){
return this.name+" "+this.getSum()+" "+this.getAvg();
};
</script>
- 기본 자료형 - 객체 차이
기본 자료형 => 메소드 생성 불가
<script>
var num=200;
alert(typeof(num)); //숫자
var objNum=new Number(200);
alert(typeof(objNum)); //객체
objNum.corona=function(){
//cf. num = 기본자료형 -> 메소드 생성 불가
return '코로나 박멸!';
};
alert(objNum.corona());
</script>
- 객체의 상속 메서드
<script>
//var obj=new Object();
//alert(obj.toString()); //toString 생략 가능
var student={
name:'홍길동',
age:26,
toString:function(){
return this.name+"은 나이가 "+this.age+"이다";
}
}
alert(student);
</script>
- 배열 객체 (내장 객체)
<script>
var nums=new Array(); //빈 배열 객체 생성
nums[0]=10;
nums[1]=20;
nums[2]=30;
alert(nums[1]);
//var fruits=['바나나','사과','수박','참외']
var fruits=new Array('바나나','사과','수박','참외');
alert(fruits);
</script>
- 메서드
본인 변화 : pop, push, reverse, sort, splice, unshift,..
본인 불변 (3개) : concat, join, slice
<script>
var fruits1=['바나나','사과','수박','참외'];
var fruits2=['메론','포도','감귤'];
var totalfruits=fruits1.concat(fruits2); //배열 모두 합침
var str=fruits1.join(); //배열을 하나의 문자열로 만듦 //구분 기호 x => ,로 연결
fruits1.push("복숭아","망고"); //배열 뒤에 추가
fruits2.unshift("배"); //배열 앞에 추가
fruits1.pop(); //맨뒤 배열 요소 추출
fruits2.shift(); //맨앞 배열 요소 추출
fruits3=['바나나','사과','딸기'];
fruits4=['귤','메론','포도'];
fruits3.splice(2); //두번째 위치부터 요소 모두 삭제, 추가 //바나나,사과
var nums=[10,20,30,40,50,60];
nums.splice(3); // 10,20,30
fruits4.splice(2,1); //두번째위치부터 한개 삭제
fruits4.splice(2,1,'딸기','파인애플');
//2번째 위치 요소 한개(포도) 삭제, 해당 위치에 새 요소 추가
var fruits5=['메론','포도','감귤','배'];
fruits5.splice(2,0,"복숭아"); //2번째 위치에 삽입 (삭제 X)
var fruits=['귤','메론','포도','키위','딸기'];
var newFruits=fruits.slice(2); //2번째 요소부터 선택, 변수에 담음
console.log(newFruits); //포도, 키위, 딸기
var sFruits=fruits.slice(1,4); //1~3번째 요소 따로 담음 (4번째 X)
console.log(sFruits) //메론, 포도, 키위
console.log(fruits.sort()); //오름차순 정렬 //귤, 딸기, 메론, 키위, 포도
console.log(fruits.reverse()); //내림차순 정렬 (거꾸로)
</script>
- addEventListener : document 내 특정 요소에 이벤트 등록
<script>
function hello(){
alert("안녕");
}
window.onload=function(){
var ja=document.querySelector("#js");
ja.addEventListener("click",hello); // (실행 조건 이벤트(click, mouseover, mouseout), 실행할 함수)
};
</script>
<body>
<h1 id="js">자바 스크립트 시작</h1>
</body>
- ex. 여행 준비물 점검 목록
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
|
<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>여행 준비물 점검 프로그램</title>
<style>
#contents{
width: 620px;
margin: 0 auto;
}
#contents h2{
text-align: center;
}
#form{
background-color: #007acc;
padding: 30px 40px;
color: #fff;
text-align: center;
}
#form input{
border: 1px solid #ccc;
width: 440px;
padding: 10px;
}
#form .addBtn{
padding: 10px;
width: 60px;
border: 1px solid #ccc;
background-color: #fff;
color: #555;
box-shadow: 1px 2px 4px #167dae;
text-align: center;
font-size: 0.9em;
cursor: pointer;
}
#itemList ul{
list-style: none;
margin: 0;
padding: 0;
}
#itemList li{
position: relative;
cursor: pointer;
padding: 12px 8px 12px 40px;
background-color: #eee;
font-size: 1.2em;
transition: all 0.5s;
}
#itemList ul li:nth-child(odd){
background-color: #f9f9f9;
}
#itemList ul li:hover{
background-color: #ccc;
}
#itemList .close{
position: absolute;
top: 0;
right: 0;
padding: 12px 16px;
background-color: rgba(255,255,255,0.2);
}
#itemList .close:hover{
background-color: #f00;
color: #fff;
}
</style>
<script>
var itemList=[]; //입력값 넣을 목록
window.onload=function(){
var addButton=document.querySelector("#add");
var input=document.querySelector("#item");
addButton.addEventListener("click",addList); //추가 버튼 누르면 addList 함수 실행
input.addEventListener("keydown", function(e){
if(e.keyCode==13){ //키보드 이벤트 : 엔터
addList(); //input에서 엔터 치면 addList 함수 실행
}
});
};
//사용자정의함수 (목록에 추가)
function addList(){
var item=document.querySelector("#item").value; //input 입력값 item 변수에 넣음
if (item!==""){ //입력값 있으면 itemList 배열 목록에 추가
itemList.push(item);
document.querySelector("#item").value=""; //input 창 비우기
document.querySelector("#item").focus(); //input 창에 커서
showList(); //목록 표시하는 함수 실행
} else{
alert("준비물을 입력해주세요.");
}
};
// 사용자정의함수 (목록 표시)
function showList(){
var list="<ul>";
for (var i=0;i<itemList.length;i++){ //배열 길이만큼 (1개면 itemList[0]만) list 대입
list+= "<li>"+itemList[i]+"<span class='close' id="
+i+">X</span></li>";
}
list+="</ul>";
document.querySelector("#itemList").innerHTML=list; //Selector=> id에 적용
//list를 html #itemList 태그에 표시 var remove=document.querySelectorAll('.close'); //SelectorAll=> class에 적용
//X버튼 객체를 remove 변수에 전달
for (var i=0;i<remove.length;i++){ remove[i].addEventListener("click",removeList);
//클릭한 X버튼 객체는 removeList 함수 실행
}
};
//사용자정의함수 (목록에서 삭제, 새 목록 표시)
function removeList(){
var id=this.getAttribute("id");
//클릭한 X버튼 객체의 id 찾음 <= showList에서 각 span의 id에 숫자 부여했음 itemList.splice(id,1); //클릭한 버튼 객체 itemList에서 삭제
showList();
//변경된 itemList배열을 다시 화면에 표시 (없으면 화면에서 삭제되지 X)
};
</script>
</head>
<body>
<div id="contents">
<h2>여행 준비물 점검 목록</h2>
<div id="form">
<input type="text" id="item" autofocus="true">
<button type="button" id="add" class="addBtn">추가</button>
</div>
<div id="itemList">
</div>
</div>
</body>
|
cs |
- ex. this
[JS] 자바스크립트에서의 this
this는 이것을 뜻합니다! (그러니까 '이게' 뭐죠...... 😵) 자바스크립트 내에서 this는 '누가 나를 불렀느냐'를 뜻한다고 합니다. 즉, 선언이 아닌 호출에 따라 달라진다는 거죠. 그럼 각 상황별로 th
nykim.work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<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>문서객체모델</title>
<script>
window.onload=function(){
var a=document.querySelector("#title");
var b=document.querySelectorAll(".ta");
a.onclick=function(){
a.style.color="red";
};
b[0].onclick=function(){
this.style.color="blue"; //this: 나 자신 (b[0])
};
};
</script>
</head>
<body>
<h1 id="title">대한민국</h1>
<p class="ta">ddd</p>
<p class="ta">aaaa</p>
</body>
|
cs |
'Programming > 국비학원' 카테고리의 다른 글
220706 - 자바스크립트 - DOM (0) | 2022.07.07 |
---|---|
220705 - 자바스크립트 - 객체, BOM (0) | 2022.07.06 |
220701 - 자바스크립트 - 객체 생성, 객체의 배열화, 내장 객체 (0) | 2022.07.02 |
220630 - 자바스크립트 - 반복문, 함수, 객체 (0) | 2022.07.01 |
220629 - 자바스크립트 - 변수, 연산자, 조건문(if, switch, 삼항연산자, 짧은 조건문), 반복문(for문, 향상된 for문) (0) | 2022.06.30 |