JavaScript

JavaScript(date, window, setTimeout, setInterval, 시계만들기, location, form)

code2772 2022. 11. 7. 16:06
728x90
반응형

✔ Date 객체 
날짜, 시간등을 쉽게 처리할 수 있는 내장 객체

연도(year)
- 2자리로 연도를 표기 : 1900 ~ 1999sus
- 4자리로 연도를 표기 : 2000 ~

월(month)
- 0(1월) ~ 11(12월)

Date 객체를 생성하는 방법
new Date() : 현재 날짜 시간을 저장한 객체가 생성
new Date('날짜 문자열') : 해당 특정 날자와 시간을 저장한 객체가 생성
new Date('밀리초') : 1970년 1월 1일 0시 0분 0초 ~ 해당 밀리초만큼 지난 날짜와 시간을 저장한 객체가 생성
new Date(년, 월, 일 , 시, 분 ,초 ,밀리초) : 해당 특정 날자와 시간을 저장한 객체가 생성

 

console.log(new Date()); // 내 OS 시간을 가저온다.
console.log(new Date(22,11,7)); // 년도를 2자리로 사용하면 1900년도
// 1922-12-06
// console.log(new Date(2022,10,7,13,40,00));
const current_time  = new Date(2022,10,7,13,40,00);
console.log(current_time);
console.log(current_time.toString()); //표준시로 출력


console.log(`현재 년도 : ${current_time.getFullYear()}`);
console.log(`현재 월 : ${current_time.getMonth()+1}`);
console.log(`현재 일 : ${current_time.getDate()}`);
console.log(`현재 시간 : ${current_time.getHours()}`);
console.log(`현재 분 : ${current_time.getMinutes()}`);
console.log(`현재 초 : ${current_time.getSeconds()}`);

console.log(new Date(1700000000000));

BOM(Browser Object Model) : 비표준
웹 브라우저에 구현된 javascript 객체 모델을 의미하며 window 객체의 프로퍼티로 조회가 가능

✔ window 객체
웹 브라우저의 창이나 탭을 표현하기 위한 객체들이며 웹 브라우저는 window 객체를 이용하여 브라우저 창을 표현할 수 있음

<!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>window 객체</title>

    <script>
        for(let wins in window){
            console.log(`property : ${wins} value ${window[wins]}`);
        }
    </script>

</head>
<body>
    <h2>window 객체</h2>
   
</body>
</html>


✔ setTimeout()  // 시간이 지난 후 한번 수행
일정 시간이 지난 후 매개변수로 제공된 함수를 실행

    const 함수명 = function(){
        실행문;
        ...
    }

    cosnt st = setTimeout(함수명, 시간);

<!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>setTimeout</title>
    <script>
        const hello = function(){
            alert(`안녕하세요. JavaScript!`)
        }
        const st = window.setTimeout(hello, 2000); //2초 콜벡함수
        clearTimeout(st);// 실행을 막는것으로 생각하자.
    </script>
</head>
<body>
    <h2>setTimeout</h2>
</body>
</html>

✔ setInterval()
일정 시간마다 매개변수로 제공된 함수를 실행

clearTimeout()

setTimeout()를 취소함

clearInterval()

setInterval()를 취소함

 

<!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>setInterval</title>
    <script>
        const hello = function(){
            console.log(`안녕하세요. JavaScript!`);
        }
        const si = setInterval(hello, 2000);//window는 생략이 가능하다.

        const clearInter = function(){
            clearInterval(si);
            console.log(`hello() 중지되었음!`);
        }
    </script>
</head>
<body>
    <h2>setInterval</h2>
    <p><button onclick="clearInter()">중지</button></p>
</body>
</html>

 

 

✔ 문제(시계만들기).
setInterval(), clearInterval를 사용하여 아래와 같은 시계 프로그램을 만들어보자.
    14:20:1
    14:20:2
    ......
    14:20:10 <------  종료 버튼을 누르면 시간이 멈춤
    14:20:49 <------  시작 버튼을 누르면 다시 시간이 진행됨

    [종료] 누를 시 끝 [시작]을 누르면 다시 시작

 

<!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>시계</title>
    <script>

        function printTime(){
            const date = new Date();
            const hh =date.getHours();
            const mm =date.getMinutes();
            const ss = date.getSeconds();
            console.countReset(`${hh}:${mm}:${ss}`);
        }

        let timeId = null;

        function startClock(){
          timeId =  setInterval(printTime, 1000);
          console.log(`start`)
        }
       
        function stopClock(){
            timeId = clearInterval(timeId);
            console.log(`stop`)
        }

// const time  = function(){
//     console.log(new Date());
 
// }
//         let si = setInterval(time, 1000);//window는 생략이 가능하다.
//         const clearInter = function(){
//             clearInterval(si);
//             console.log(`중지되었음!`);
//         }

//         const set = function(){
//              si = setInterval(time, 1000);
//             console.log(`다시시작`);
//         }

    </script>
</head>
<body>
    <h2>시계</h2>
    <p><button onclick="startClock()">시작</button></p>
    <p><button onclick="stopClock()">종료</button></p>
</body>
</html>
 
✔ location 객체
현재 브라우저에 표시된 HTML 문서의 주소를 얻거나, 브라우저에 새 문서를 불러올 때 사용


   http://dj-koreaitaca.net/renewal2021/community/post.asp
    ------  --------------- ------------------------------
    protocol    hostname            pathname

    protocol : 콜론을 포함하는 https, http, ftp등 프로토콜 정보를 리턴
    hostname : 호스트의 이름과 포트번호를 리턴
    pathname : URL 겨올부분의 정보를 리턴
    href : 페이지 URL 전체 정보를 리턴 또는 URL을 지정하여 페이지를 이동
<!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>location</title>
    <script>
        // location.href = 'https://www.google.co.kr'
        console.log(`현재 문서의 URL주소 : ${location.href}`);
        console.log(`현재 문서의 protocol : ${location.protocol}`);
        console.log(`현재 문서의 hostname : ${location.hostname}`);
        console.log(`현재 문서의 pathname : ${location.pathname}`);

        function sendit(){
            location.href = 'https://www.google.co.kr'// 이동
            // 함수 처리를 하지 않으면 바로 이동한다.
        }
       
    </script>
</head>
<body>
    <h2>location</h2>
    <p><button onclick = "sendit()">이동</button></p>
</body>
</html>
 
✔ form 객체
일반적인  폼에 접근할 때 사용, document.forms 컬렉션을 이용해서 접근

    <form name = "myform" id = "regform" methode = "post" action ="regist.jsp">
        아이디 : <input type = "text" name ="userid" id = "id"><br>
        비밀반허 : <input type = "password" name ="userpw" id = "pw"><br>
    </form>

폼 접근
const frm = document.myform; // body부분을 document이다. // name을 찾음
const frm = deocument.getElementById('regform'); //아이디를 찾아줘
const frm = document.forms['myform'] // name 으로
const frm = document.forms[0]; // 첫 번째 폼을 찾아라

아이디 입력상자 접근
const userid = frm.userid; (name)
const userid = document.getElementById('id'); // 바로
const userid = document.forms['myform'].elements[0];
const userid = document.forms['myform'].elements['userid'];
const userid = document.forms[0][0];
<!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>form</title>

</head>
<body>
    <h2>form</h2>
    <form action="#" name = "frm1">
        <input type="text" name = "userid" id="id" placeholder ="아이디 입력"><br>
        <input type="password" name = "userpw" placeholder="비밀번호 입력">
    </form>

    <form action="#" name = "frm2">
        <input type="search" name = "search" placeholder ="검색어 입력"><br>
    </form>
    <script>
        const frm1 = document.frm1;
        console.log(frm1.userid.placeholder);

        const frm2 = document.frm2;
        console.log(frm2.search.placeholder)

        document.getElementById('id').value = 'apple';

        document.forms['frm1'].elements['userpw'].value = '1004';

        document.forms[1].elements[0].value = '코리아it아카데미'

    </script>
</body>
</html>
반응형