<이전 포스팅 정리>
class
사용자 정의 객체-문법
사용법
내장객체
기본객체
- BOM
- DOM
=> www.w3schools.com
=> https://developer.mozilla.org/ko
외부객체
< 8월 달력 출력하기 >
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/css">
</script>
</head>
<body>
<script type="text/javascript">
//달력만들기
const year=2023;
const month=8;
const start=new Date(year,month-1,1);
const end=new Date(year,month,1-1);
//1일 요일 (일요일을 1로 잡음 원래 0임)
const startDayOfWeek =start.getDay()+1;
//마지막날짜(한달날짜)
const endDate=end.getDate();
let html="";
let html2="";
html2+='<table border="1" width="200">'; //html2는 년도와 월 그리고 요일/일수를 세로로 배치하기 위해 테이블을 하나 더 만든것이다
html2+='<tr>';
html2+= '<td align="center">'+year+"년"+month+"월"+'</td>';
html2+='</tr>';
html2+='<tr>';
html+='<table border="1" width="200">';
html+='<tr>';
html+='<th align="center">'+"일"+"</th>"; //요일
html+='<th align="center">'+"월"+"</th>";
html+='<th align="center">'+"화"+"</th>";
html+='<th align="center">'+"수"+"</th>";
html+='<th align="center">'+"목"+"</th>";
html+='<th align="center">'+"금"+"</th>";
html+='<th align="center">'+"토"+"</th>";
html+='</tr>';
html+='<tr>';
for(let i=1;i<startDayOfWeek;i++){
html+='<td></td>';
} //앞뒤 공백
for(let date=1;date<=5;date++){
html+='<td align=center>'+date+'</td>';
}
html+='</tr>';
let date=6; //일수 6부터 시작 ~ 26일까지 나타내기
for(let row=0;row<3;row++){
html+='<tr>';
for(let col=0;col<7;col++){
html+='<td align="center">'+date+"</td>";
date++;
}
html+='</tr>';
}
html+='<tr>'; //27~31일 표현
for(let date=27;date<32;date++){
html+='<td align=center>'+date+'</td>';
}
html+='<td></td>'+'<td></td>'; //남은 일수 공백
html+='</tr>';
html+='</table>';
html2+='<td>'+html+'</td>'; //html2에 html표 집어넣기
html2+='</tr>';
html2+='</table>';
document.write(html2); //html이 들어있는 html2를 나타낸다.
</script>
</body>
</html>
결과
[window함수] - 내장함수
*screen위치 나타내기
<script type="text/javascript">
//window= browser
//배열 /Map
console.log(window['screenTop']); //창이 위에서 아래로 갈수록 값이 커짐
console.log(window['screenLeft']); //창이 왼쪽에서 오른쪽으로 갈수록 값이 커짐
console.log(window.screenTop);
console.log(window.screenLeft);
</script>
*screen 새로운 창 버튼으로 열고 닫기
<script type="text/javascript">
let child;
const openWindow= function(){
child=open('./gugudan2.html','winopen', "width=400,height=600,left=30,top=40"); //원격이든 로컬이든 상관없이 사용가능
};
const closeWindow=function(){ //열었던 창을 닫을 수 있게 하는 함수
child.close();
};
</script>
</head>
<body>
<script type="text/javascript">
//window.open()
//tab방식으로 열림
console.log(window.screenTop);
//설정한 크기의 새로운 창으로 열리게 된다.
</script>
<button onclick="openWindow()">창열기</button>
<button onclick="closeWindow()">창닫기</button>
</body>
+) 창을 정가운데 위치하도록 하려면
<script type="text/javascript">
let top2 = screen.height/2 - 300;
let left2=screen.width/2-200;
open('https://m.daum.net','winopen', "width=400,height=600,left="+left2+",top="+top2); //따로 지정한 변수를 ''안에 적용할 때는 문자열의 합으로 적용하도록 한다.
</script>
=> top=창의 세로 전체 크기/2-지정한 창의 높이/2
=> left=창의 가로 전체 크기/2-지정한 창의 너비/2
[history] - 페이지 이동(이전페이지/다음페이지)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const goBack=function(){
//history.back(); //이전페이지로 돌아갈 수 있도록 함
history.go(-1);
};
</script>
</head>
<body>
<script type="text/javascript">
console.log(history.length); //방문 기록에 저장된 목록의 개수를 반환
</script>
<button onclick="goBack()">뒤로가기</button>
</body>
</html>
[location] - 해당 URL로 자동이동
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
/* const goURL=function(){
};
*/
const goURL=function(url){
location.href=url;
};
//클릭 후 10초 후에 자동이동
const secURL=function(url){
setTimeout(()=>location.href=url,10000); //setTimeout메서드를 이용해 10초 후에 자동이동 되도록 함
};
</script>
</head>
<body>
<script type="text/javascript">
//경로 재지정(리다이렉션)
</script>
<button onclick="goURL()">자동이동</button>
<br/> <br/>
<button onclick="goURL('https://m.daum.net')">다음 자동이동</button>
<br/> <br/>
<button onclick="secURL('https://m.daum.net')">10초후 자동이동</button>
</body>
</html>
[DOM] - document
<input type="checkbox" name="ch1" value="apple">
<input type="button" value="계산하기" onclick="checkfrm()"/>
(중요) input을 할 때는...
1) input에 대한 타입 지정
2) 해당 input의 name(아이디) / value (이름) 지정
3) input을 클릭하거나 특정 이벤트가 있을때 처리할 함수 지정
* js에서 body쪽의 script form에 접근하는 방법
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
</script>
</head>
<body>
<form name="frm1" action="./form_ok1.html"></form>
<form name="frm2" action="./form_ok2.html"></form>
<script type="text/javascript"> //js에서 body쪽 form에 접근하는 방법
//form에 대한 입력값 검사
console.log(typeof document.forms);
//영문 복수- 배열
console.log(document.forms);
console.log(document.forms.length);
//form에 배열주소로 접근
console.log(document.forms[0]); //<form name="frm1"></form>
console.log(document.forms[1]); //<form name="frm2"></form>
//form에 form이름으로 접근
console.log(document.frm1);
console.log(document.frm2);
console.log(document.frm1.action);
</script>
</body>
</html>
- form을 정의 후에 script가 해당 form에 접근하는 방법에는 2가지가 있다
1) form에 배열주소로 접근
2) form에 name을 지정해 해당 이름으로 접근
*계산기 프로그램(예외처리)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const checkfrm=function(){
//입력값 검사 (입력여부)
if(document.frm1.num1.value.trim()==''){ //예외처리(숫자를 입력하지 않았을 때 나타남)
alert('첫번째 수를 입력하셔야 합니다')
}else if(document.frm1.num2.value.trim() == ''){ //trim을 통해 입력칸의 공백 또한 없앨 수 있다.
alert('두번째 수를 입력하셔야 합니다')
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result= num1+num2;
document.frm1.result.value=result; //value넣는거 조심하기
}
}
</script>
</head>
<body>
<form name="frm1">
<!--간단한 계산기 프로그램
입력받은 데이터는 문자열이기 때문에 형변환 해줘야 함다-->
<input type="text" name="num1"/>
+
<input type="text" name="num2"/>
=>
<input type="button" value="계산하기" onclick="checkfrm()"/>
=>
<input type="text" name="result" readonly/>
</form>
</body>
</html>
#주의할 것 => form에서 입력받은 데이터는 숫자가 아닌 문자이기 때문에 계산과정이 있을 때는 형변환을 해주어야 한다.
=> parseInt
* 문자열 변환 프로그램 (이름 첫글자 대문자로 바꾸기)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const checkfrm=function(){ //이름 입력받고 처리하는 함수
if(document.frm1.name.value.trim()==''){ //예외처리(숫자를 입력하지 않았을 때 나타남)
alert('이름을 입력하셔야 합니다')
}else{
let name = document.frm1.name.value.trim();
//console.log(name);
let result = capitalize(name);
document.frm1.result.value=result;
}
};
const capitalize=function(sentence){ //이름첫글자 대문자로 바꿔주는 함수
let words=sentence.split(' '); //split공백으로 나누는 순간 배열의 방식으로 사용 가능해짐
// 따라서 모양새는 ['hong', 'gil', 'dong']이런식으로 나누어 지며, hong gil dong 해당 문장이 공백 포함 인덱스로 이름지어지게됨
let result=' '; //result에는 문자열을 일렬로 표현하기 위함
for(let i=0;i<words.length;i++){
result+= words[i].substring(0,1).toUpperCase()+ words[i].substring(1)+' ';
//0부터 1까지 문자열을 분리한다음 대문자 적용. 인덱스 1부터 나머지 문자열들은 그냥 이어 붙임
//맨 뒤에 공백을 붙여줘야 SonSooBin이 아닌 Son Soo Bin이 된다.
}
//console.log(result);
return result;
};
</script>
</head>
<body>
<form name="frm1">
<!--첫 문자를 대문자로 변경하는 프로그램-->
<input type="text" name="name"/>
=>
<input type="button" value="변경하기" onclick="checkfrm()"/>
=>
<input type="text" name="result" readonly/>
</form>
</body>
</html>
*비밀번호 form
<script type="text/javascript">
const checkfrm=function(){
console.log(document.frm1.name.value);
//실제 내용이 암호화 된것은 아님
console.log(document.frm1.password.value);
console.log(document.frm1.memo.value);
};
</script>
</head>
<body>
<form name="frm1">
<input type="text" name="name"/>
<br/><br/>
<input type="password" name="password"/>
<br/><br/>
<textarea name="memo"></textarea>
<br/><br/>
<input type="button" value="내용확인" onclick="checkfrm()"/>
</form>
</body>
*선택 form (check box형식)
<script type="text/javascript">
const checkfrm=function(){
/*
console.log(document.frm1.ch1.checked);
console.log(document.frm1.ch2.checked);
console.log(document.frm1.ch3.checked);
console.log(document.frm1.ch4.checked);
console.log(document.frm1.ch1.value);
console.log(document.frm1.ch2.value);
console.log(document.frm1.ch3.value);
console.log(document.frm1.ch4.value);
};
*/
if(document.frm1.ch1.checked){ //선택한 과일의 내용만 출력이 될 수 있도록 함
console.log(document.frm1.ch1.value);
}
if (document.frm1.ch2.checked){
console.log(document.frm1.ch2.value);
}
if(document.frm1.ch3.checked){
console.log(document.frm1.ch3.value);
}
if(document.frm1.ch4.checked){
console.log(document.frm1.ch4.value);
}
}
</script>
</head>
<body>
<form name="frm1">
<input type="checkbox" name="ch1" value="apple">사과<br/>
<input type="checkbox" name="ch2" value="watermelon">수박<br/>
<input type="checkbox" name="ch3" value="strawberry">딸기<br/>
<input type="checkbox" name="ch4" value="kiwi">키위<br/>
<br/><br/>
<input type="button" value="내용확인" onclick="checkfrm()"/>
</form>
</body>
*선택 form2 (전체선택/전체해제)
<script type="text/javascript">
const checkfrm=function(){ //선택한 것의 내용 보여주기
//console.log(document.frm1.ch.length);
for(let i=0; i<document.frm1.ch.length;i++){
if(document.frm1.ch[i].checked){
console.log(document.frm1.ch[i].value);
}
}
};
const checkAll=function(){ //전체 선택
for(let i=0; i<document.frm1.ch.length;i++){
document.frm1.ch[i].checked=true;
}
};
const clearAll=function(){ //전체 해제
for(let i=0; i<document.frm1.ch.length;i++){
document.frm1.ch[i].checked= false;
}
};
</script>
</head>
<body>
<form name="frm1">
<input type="button" value="전체선택" onclick="checkAll()"/>
<input type="button" value="전체해제" onclick="clearAll()"/>
<br/><br/>
<input type="checkbox" name="ch" value="apple">사과<br/>
<input type="checkbox" name="ch" value="watermelon">수박<br/>
<input type="checkbox" name="ch" value="strawberry">딸기<br/>
<input type="checkbox" name="ch" value="kiwi">키위<br/>
<br/><br/>
<input type="button" value="내용확인" onclick="checkfrm()"/>
</form>
</body>
*연산자 선택 계산기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const Cal=function(){
let num=document.frm1.cal.options[document.frm1.cal.options.selectedIndex].value;
switch(num){
case '+':
Plus();
break;
case '-':
Minus();
break;
case 'x':
Multi();
break;
case '/':
Div();
break;
}
}
const Plus=function(){
if(document.frm1.num1.value.trim()==''){ //예외처리(숫자를 입력하지 않았을 때 나타남)
alert('첫번째 수를 입력하셔야 합니다')
}else if(document.frm1.num2.value.trim() == ''){ //trim을 통해 입력칸의 공백 또한 없앨 수 있다.
alert('두번째 수를 입력하셔야 합니다')
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result= num1+num2;
document.frm1.result.value=result;
}
};
const Minus=function(){
if(document.frm1.num1.value.trim()==''){
alert('첫번째 수를 입력하셔야 합니다')
}else if(document.frm1.num2.value.trim() == ''){
alert('두번째 수를 입력하셔야 합니다')
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result= num1-num2;
document.frm1.result.value=result;
}
};
const Multi=function(){
if(document.frm1.num1.value.trim()==''){
alert('첫번째 수를 입력하셔야 합니다')
}else if(document.frm1.num2.value.trim() == ''){
alert('두번째 수를 입력하셔야 합니다')
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result= num1*num2;
document.frm1.result.value=result;
}
};
const Div=function(){
if(document.frm1.num1.value.trim()==''){
alert('첫번째 수를 입력하셔야 합니다')
}else if(document.frm1.num2.value.trim() == ''){
alert('두번째 수를 입력하셔야 합니다')
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result= num1/num2;
document.frm1.result.value=result;
}
};
</script>
</head>
<body>
<form name="frm1">
<!--간단 계산기 프로그램-->
<br/><br/>
<input type="text" name ="num1"/>
<select name="cal"> <!--각 연산-->
<option value="+">+</option>
<option value="-">-</option>
<option value="x">x</option>
<option value="/">/</option>
</select>
<input type="text" name="num2" size="10"/>
=>
<input type="button" value="내용확인" onclick="Cal()"/>
=>
<input type="text" name="result" size="10" readonly/>
</form>
</body>
</html>
- 어떤 값을 사용자에게 입력받을 때는 여러 형식이 form에 들어올 수 있으니 특정 형식 이외의 값들은 예외처리를 해주어 들어오지 못하게 해야 오류가 나지 않는다.
+) value와 내용을 추출할 때는 아래의 코드로 적으면 된다.
console.log(document.frm1.sel.options[document.frm1.sel.options.selectedIndex].value); //value값 추출
console.log(document.frm1.sel.options[document.frm1.sel.options.selectedIndex].text); //내용 추출
*태그 내용 확인
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const viewTag = function(){
//html 일부분을 선택
//css의 selector(id(1개), class(집합), tag(집합))
/*
let h1 = document.getElementById('h1');
let h2 = document.getElementById('h2');
console.log(h1);
console.log(h1.innerHTML); // 태그 안의 내용을 보고 싶을 때 사용
console.log(h2);
*/
let h2s =document.getElementsByTagName('h2');
//console.log(h2s);
//console.log(h2s.length);
//console.log(h2s[0]);
for(let i=0;i<h2s.length;i++){
console.log(h2s[i]);
console.log(h2s[i].innerHTML);
}
/*h2s.forEach(element => { //foreach는 따로 지원을 하지 않기 때문에 사용할 수 없다.
console.log(element);
});*/
//document.getElementsByClassName
}
</script>
</head>
<body>
<input type="button" value="tag보기" onclick="viewTag()"/> <!--버튼으로 호출하여 html가져오기-->
<br /><hr /><br />
<h2 id="h1">Header1</h2> <!--id는 중복 X-->
<h2 id="h2">Header2</h2>
<h2 id="h3">Header3</h2>
</body>
</html>
*css selector이용
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const viewTag = function(){
//css selector이용
//document.querySelector(selector) -id
//document.querySelectorAll(selector) - tag, class
let h2s=document.querySelectorAll('.c1');
for(let i=0;i<h2s.length;i++){
console.log(h2s[i].innerHTML);
}
// let h1=document.querySelector('#h1');
//console.log(h1);
//console.log(h1.innerHTML);
//console.log(h11);
};
</script>
</head>
<body>
<input type="button" value="tag보기" onclick="viewTag()"/> <!--버튼으로 호출하여 html가져오기-->
<br /><hr /><br />
<h2 id="h1" class="c1">Header1</h2> <!--id는 중복 X-->
<h2 id="h2" class="c1">Header2</h2>
<h2 id="h3" class="c1">Header3</h2>
</body>
</html>
- c1의 class를 가진 모든 태그들의 내용을 querySelectorAll을 통해 배열처럼 사용할 수 있다.
*tag내용 확인/변경
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const viewTag = function(){
let div1=document.getElementById('div1');
console.log(div1.innerHTML); //html 형식
console.log(div1.textContent); //html 제거
};
const modifyTag=function(){ //html내용을 변경
let div1=document.getElementById('div1');
//메모리에서만 변화가 일어난다.
//div1.innerHTML='new content';
//div1.innerHTML='<h2>new content</h2>'; //html태그 또한 변경가능
div1.textContent='<h2>new content</h2>'; //html태그 또한 문자열 취급을 하기 때문에 태그가 적용이 되는 것이 아닌 태그도 같이 화면에 출력이 된다.
};
</script>
</head>
<body>
<input type="button" value="tag보기" onclick="viewTag()"/>
<br /><hr /><br />
<input type="button" value="tag변경" onclick="modifyTag()"/>
<br /><hr /><br />
<div id="div1">content</div>
<div id="div2">
<h2>content</h2>
</div>
</body>
</html>
- 특정 태그의 내용을 getElementById로 내용을 변경시킬 수 있다.
*범위가 있는 구구단 출력
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
const checkfrm=function(){
//입력값 검사 (입력여부)
if(document.frm1.num1.value.trim()==''){ //예외처리(숫자를 입력하지 않았을 때 나타남)
alert('시작단수를 입력하셔야 합니다');
}else if(document.frm1.num2.value.trim() == ''){ //trim을 통해 입력칸의 공백 또한 없앨 수 있다.
alert('끝단수를 입력하셔야 합니다');
}else if(document.frm1.num1.value.trim()>document.frm1.num2.value.trim()){
alert('시작단수를 끝단수보다 더 작게 입력하세요');
}else{
let num1=parseInt(document.frm1.num1.value);
let num2=parseInt(document.frm1.num2.value);
let result =document.getElementById('result');
result.innerHTML=gugudan(num1,num2);
}
};
const gugudan=function(start,final){ //html(구구단 표 나타내는 함수)
let html= '<table border="1" width="200">';
for(let row=start;row<=final;row++){
html+='<tr>';
for(let col=1;col<=9;col++){
html+= '<td align=center>'+row+'x'+col+'='+row*col+'</td>'; //html에 계속 쌓아가면서 만들기
}
html+= '</tr>';
}
html+='</table>';
return html;
};
</script>
</head>
<body>
<form name="frm1">
시작단수
<input type="text" name="num1"/>
~ 끝단수
<input type="text" name="num2"/>
<input type="button" value="구구단 출력" onclick="checkfrm()"/>
<hr/>
<div id="result"></div>
</body>
</html>
*동적이벤트 생성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
//기능은 스크립트 디자인은 html로
//브라우저가 html문서를 전부 읽으면 - event
window.onload=function(){
let btn1= document.getElementById('btn1');
//console.log(btn1);
//동적이벤트 생성 (event를 동적으로 주면 onload를 붙여야한다.)
btn1.onclick=function(){
alert('클릭');
};
document.getElementById('btn2').onclick=function(){
alert('클릭2');
};
document.getElementById('btn3').onmouseover=function(){ //onmouseover=>마우스를 올리기만 해도 팝업이 뜨게 된다.
alert('클릭3');
};
};
</script>
</head>
<body>
<!--event-->
<input type="button" id="btn1" value="클릭"/>
<input type="button" id="btn2" value="클릭2"/>
<div id="btn3">클릭</div> <!--버튼이 아니어도 가능하다-->
<script type="text/javascript">
//let btn1= document.getElementById('btn1');
//console.log(btn1);
</script>
</body>
</html>
- 태그 내용 변경 관련 내용 좀 더 공부가 필요함
- 웹페이지 만들기 위한 소스들 수집하기