for ~ in

in 으로 for문을 써서 array 접근

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> for ~ in</title>

    </head>

    <body>

        <script>

            var student = {  //object literal

                                  hakbun:'1101',

                                  irum : '한송이',

                                  kor : 100,

                                  eng : 89,

                                  mat : 77 

                                   };

            document.write("학생이름 : " + student.irum + "<br>");

            document.write("수학 점수 : " + student['mat']);  

            document.write("<p>학생 객체의 맴버 프라퍼티는 아래와 같습니다.</p>");                    

            for(var i in student){

                document.write(i + " --> " + student[i] + "<br>");

            }

            if("total" in student){

                document.write("total 프라퍼티는 있습니다.");

            }else{

                document.write("total 프라퍼티는 없습니다.");

            }

            student.total = student.kor + student.eng + student.mat;

            student.avg = student.total / 3.;

            delete student.hakbun;

            document.write("<hr>");

            for(var i in student){

                document.write(i + " --> " + student[i] + "<br>");

            }

        </script>

    </body>

</html>


출력:

학생이름 : 한송이

수학 점수 : 77

학생 객체의 맴버 프라퍼티는 아래와 같습니다.


hakbun --> 1101

irum --> 한송이

kor --> 100

eng --> 89

mat --> 77

total 프라퍼티는 없습니다.

irum --> 한송이

kor --> 100

eng --> 89

mat --> 77

total --> 266

avg --> 88.66666666666667

-----------------------------------

for ~ in 1

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>for ~ in</title>

    </head>

    <body>

    <script>

        var array = [100, "한송이", true, 'A', 89.555555];

        for(var i in array){  //i는 인덱스

            document.write(i + " --> " + array[i] + "<br>");

        }

    </script>

    </body>

</html>

출력:

0 --> 100

1 --> 한송이

2 --> true

3 --> A

4 --> 89.555555

-------------------------------

for ~ in 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

            var fruits = ["apple", "orange", "melon", "cherry", "strawberry", "grape"];

            for(var i = 0 ; i < fruits.length ; i++){

                document.write("fruits[" + i + "] = " + fruits[i] + "<br>");

            }

            document.write("<hr>");

            for(var j in fruits){  //인덱싱을 하지않고(미리 몇개 있는지 계산하며 도는 것이 아니고, 모든 것이 끝날 때까지 돈다. 이 방법이 더 빠름.

                document.write("fruits[" + j + "] = " + fruits[j] + "<br>");

            }

        </script>

    </body>

</html>

출력:

fruits[0] = apple

fruits[1] = orange

fruits[2] = melon

fruits[3] = cherry

fruits[4] = strawberry

fruits[5] = grape

fruits[0] = apple

fruits[1] = orange

fruits[2] = melon

fruits[3] = cherry

fruits[4] = strawberry

fruits[5] = grape

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

드롭다운 select , switch

이메일 형식 만들기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <style>

            input[type="text"]{

                border:1px solid #bbb;

            }

            input[name="emailId"]{

                text-align:right;

                width:100px;

            }

        </style>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                document.getElementById("emailServer").addEventListener("change", change, false);

            }

            function change(){

                var email = document.getElementById('emailServer').value;

                var domain = document.getElementById('emailDomain');

                switch(email){

                    case "hanmail": domain.value = "hanmail.net"; break; 

                    case "naver": domain.value = "naver.com"; break;

                    case "nate":  domain.value = "nate.com"; break;

                    case "gmail":  domain.value = "gmail.com"; break;

                    case "user" : domain.disabled = false;

                                       domain.value = "";

                                       domain.focus();

                }

            }

        </script>

    </head>

    <body>

        <h1>Email 을 넣어주세요.</h1>

        <form>

            <p><label for="emailServer">Email : </label>

                  <input type="text" name="emailId" autofocus> @ 

                  <input type="text" id="emailDomain" name="emailDomain" disabled>

                  <select id="emailServer" name="emailServer">

                     <option value="init">--선택--</option>

                     <option value="hanmail">hanmail</option>

                     <option value="naver">naver</option>

                     <option value="nate">nate</option>

                     <option value="gmail">gmail</option>

                     <option value="user">직접입력</option>

                  </select>                 

            </p>

        </form>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체 만들기 : object literal

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

        <script>

            //1. object literal 사용하자.

            var square = {

               width:50, 

               height:100,

               color:"yellow",

               borderColor : "black",

               getArea : function(){

                   return this.width * this.height;   //반드시 this를 사용

               }

            };

            document.write("<p>사각형의 넓이는 = " + square.getArea() + "</p>");

            square.depth = 200;

            square.set = function(w, h){

                square.width = w;

                square.height = h;

            };

            square.set(10, 30);

            document.write("<p>사각형의 넓이는 = " + square.getArea() + "</p>");

            document.write("<ul>square 객체의 멤버는 아래와 같습니다.");

            for(var i in square){

                document.write("<li>" + i + " --> " + square[i] + "</li>");

                //절대로 . 연산자를 사용하면 안됨

            }

            document.write("</ul>");

        </script>

    </body>

</html>

출력 :

사각형의 넓이는 = 5000


사각형의 넓이는 = 300


square 객체의 멤버는 아래와 같습니다.

width --> 10

height --> 30

color --> yellow

borderColor --> black

getArea --> function (){ return this.width * this.height; //반드시 this를 사용 }

depth --> 200

set --> function (w, h){ square.width = w; square.height = h; }

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체 만들기 : function literal

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

    <script>

        //2. function literal

        function square(w, h){

            this.width = w;  //반드시 this를 써야 한다. 만일 var 라고 쓰면 private이다.

            this.height = h;

            this.color = "yellow";

            this.borderColor = "black";

            this.getArea = function(){

                return this.width * this.height;   //반드시 this를 사용

            };

        }

        var s = new square(50, 100);

        document.write("<p>사각형의 넓이는 " + s.getArea() + "</p>");

        if(s instanceof square){

            document.write("자식맞아<br>");

        }

        if(s instanceof Date){

            document.write("Date 객체의 인스턴스이다.<br>");

        }else{

            document.write("Date 객체의 인스턴스가 아니다.<br>");

        }

        if(s instanceof Object){

            document.write("Object 객체의 인스턴스이다.");

        }else{

            document.write("Object 객체의 인스턴스가 아니다.");

        }

    </script>

    </body>

</html>

출력:

사각형의 넓이는 5000


자식맞아

Date 객체의 인스턴스가 아니다.

Object 객체의 인스턴스이다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

출력을 새창으로 띄우기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

        <script src="js/student.js"></script>

    </head>

    <body>

    <script>

        var chulsu = new Student('1101', '한송이', 100, 89, 77, 88);

        var w = window.open();

        w.document.open();

        w.document.writeln("<!DOCTYPE html><html lang=\"en\"><head>");

        w.document.writeln("<meta charset=\"utf-8\"><title> 결과보기 </title>");

        w.document.writeln("</head><body>");

        w.document.writeln("<h1>학생정보</h1>");

        w.document.writeln("<ul type='circle'>");

        w.document.writeln("<li>학번 : " + chulsu.hakbun + "</li>");

        w.document.writeln("<li>총점 : " + chulsu.getTotal() + "</li>");

        w.document.writeln("</ul></body></html>");

        w.document.close();

    </script>

    </body>

</html>

출력: 팝업창으로 뜸.

학생정보


    학번 : 1101

    총점 : 354

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체만들기 : object 객체를 이용하기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

    <script>

        /*var square = {

               width:50, 

               height:100,

               color:"yellow",

               borderColor : "black",

               getArea : function(){

                   return this.width * this.height;   //반드시 this를 사용

               }

            };*/

        //3. Object 객체를 이용하기

        var square = new Object();

        square.width = 50;

        square.height = 100;

        square.color = "yellow";

        square.borderColor = "#000";

        square.getArea = function(){

            return this.width * this.height;

        };

        square.setColor = function(foreColor){

            this.color = foreColor;

        };

        

        for(var i in square){

            document.write("<p>" + i + " --> " + square[i] + "</p>");

        }

        document.write("면적은 " + square.getArea());

    </script>

    </body>

</html>

출력: 함수의 출력은 ()를 붙여서

width --> 50


height --> 100


color --> yellow


borderColor --> #000


getArea --> function (){ return this.width * this.height; }


setColor --> function (foreColor){ this.color = foreColor; }


면적은 5000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

number : toFixed , toExponential , toPrecision

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Number Object </title>

    </head>

    <body>

        <script>

            var n = 1234.5678;

            //var str = n.toString();

            //document.write(typeof n + "<br>");  //number

            //document.write(typeof str);  //string

            

            //var str = n.toFixed(2);  //소수점 두자리까지.   1234.57

            //var str = n.toExponential(3);  //소수점 세자리까지 지수형으로 표현 .  1.235e+3

            //var str = n.toPrecision(5);  //전체 자릿수를 5자리만. 1234.6

            var str= n.toString(8);  //8진수로.  2322.44255527175255

            

            //document.write(typeof str+"<br>");  //string.   

            document.write(str); 

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

number : 3자리 마다 콤마 찍기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Number Object </title>

    </head>

    <body>

         <script>

             var num = 123456789123456;

             var str = num.toString();  //15자리

             var money = "";

             for(var i = str.length ; i >= 0 ; i -=3){

                 if((i - 3) <= 0)

                    money = str.substr(0, i) + money;

                 else

                     money = "," + str.substr(i - 3, 3) + money;

             }

             document.write(money);

         </script>          

    </body>

</html>

출력:

123,456,789,123,456

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

String

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = new String("Hello, World");

            document.write("<p>" + str.valueOf() + "</p>");

            document.write("<p>" + str.length + "</p>");

            str = "JavaScript";

            document.write("<p>" + str.length + "</p>");

        </script>

    </body>

</html>

출력:

Hello, World


12


10

//stirng은 변할 수 있음.

-----------------------------

string 1

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = '스트링 객체 연습';

            document.write(str.big() + "<br>");

            document.write(str.small() + "<br>");

            document.write(str.bold() + "<br>");

            document.write(str.italics() + "<br>");

            document.write(str.strike() + "<br>");

            document.write(str.fontcolor("red") + "<br>");

            document.write(str.fontsize(7) + "<br>");

            document.write("테스트" + str.sub() + "<br>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

string : indexOf, lastIndexOf, substr, slice

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Demo </title>

    </head>

    <body>

        <script>

            var str = new String("JavaScript was born in 1994 at Netscape");

            document.write("<p>" + str.indexOf('Netscape') + "</p>");  //몇번째 위치에 있는지

            document.write("<p>" + str.lastIndexOf("was") + "</p>");   //위와 차이는 만약 was가 두개가있을 경우에 앞에서부터 찾을지 뒤에서부터 찾을지

            document.write("<p>" + str.substr(23, 4) + "</p>");  //23번째부터 4개

            document.write("<p>" + str.slice(23, 27) + "</p>");  //23번째부터 26번째까지

        </script>

    </body>

</html>

출력:

31


11


1994


1994

---------------------------

string : split

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = "이름 : 조성모, 나이 : 42, 직업 : 가수";

            var array = str.split(",");

            for(var i in array){

                var array1 = array[i].split(":");

                document.write("<p>" + array1[0].fontcolor('red').fontsize(5) + " --> " + array1[1] + "</p>");

            }

        </script>

    </body>

</html>

출력:

이름 --> 조성모


나이 --> 42


직업 --> 가수

//이름, 나이, 직업은 font 준 상태

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

달력 : 월, 일 입력하면 달력 나오게

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 만년 달력 </title>

        <style>

            table{

                margin:auto;

                width:700px;

                margin-top:50px;

            }

            caption{

                font-size:1.5em;

                color:green;

                font-style:italic;

                font-weight:800;

            }

             td, th{

                border-bottom : 1px dotted #aaa;                

                width:100px;   

            }

            td{ height:70px;}

            th{

                background-color:blue;

                color:white;

                height:40px;

            }

        </style>

    </head>

    <body>

        <script>

            var str = prompt("만들고 싶은 년도와 월을 입력하세요(년과 월 사이에 콤마를 넣으세요) ");  //2014,6

            var year = str.split(",")[0];  //"2014"

            var month = str.split(",")[1];  //"6"

            var cal = new Date(parseInt(year), parseInt(month) - 1, 1);

            var space = cal.getDay(); //0:SUN

            var lastDay = function(){

               switch(month){

                   case "1":

                   case "3":

                   case "5":

                   case "7":

                   case "8":

                   case "10":

                   case "12": return 31;

                   case "4":

                   case "6":

                   case "9":

                   case "11": return 30;

                   case "2":

                    if(cal.getFullYear() % 400 == 0 || 

                               (cal.getFullYear() % 4 == 0 && cal.getFullYear() % 100 != 0))

                        return 29;

                    else return 28;

               } 

            };

            var array = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];

            document.writeln("<table>");

            document.write("<caption>" + year + "년 " + month + "월</caption>");

            document.writeln("<thead><tr>");

            for(var i = 0 ; i < array.length ; i++){

                document.write("<th>");

                document.write(array[i]);

                document.write("</th>");

            }

            document.write("</tr></thead>");

            document.write("<tbody><tr>");

            var count = 0;

            for(i = 0 ; i < space ; i++){

                document.write("<td>&nbsp;</td>");

                count++;

            }

            for(i = 1 ; i <= lastDay() ; i++){

                document.write("<td>" + i + "</td>");

                count++;

                if(count % 7 == 0){

                    document.write("</tr><tr>");

                    count = 0;

                }

            }

            for(i = 0 ; i < (7 - count) ; i++){

                document.write("<td>&nbsp;</td>");

            }

            document.writeln("</tr></tbody></table>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Date

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Date Demo </title>

    </head>

    <body>

        <script>

            var today = new Date();

            document.write("<p>" + today + "</p>");

            

            var aaa = new Date(2010, 9, 23, 06, 30, 0, 0);

            document.write("<p>" + aaa + "</p>");

            

            var bbb = Date.parse("May 29 2014 12:00:00");

            document.write("<p>" + bbb + "</p>");

            var someday = new Date(bbb);

            document.write("<p>" + someday + "</p>");

        </script>

    </body>

</html>

출력:

Thu May 29 2014 16:05:38 GMT+0900 (Korea Standard Time)


Sat Oct 23 2010 06:30:00 GMT+0900 (Korea Standard Time)


1401332400000


Thu May 29 2014 12:00:00 GMT+0900 (Korea Standard Time)

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Date 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Date Demo </title>

    </head>

    <body>

        <script>

           var today = new Date();

           var array = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];

           var str = "<p>지금은 " + today.getFullYear() + "년 " +

                         (today.getMonth() + 1) + "월 " +

                         today.getDate() + "일 " +

                         array[today.getDay()] + 

                         today.getHours() + "시 " +

                         today.getMinutes() + "분 " +

                         today.getSeconds() + "초 입니다.";

            document.write("<p>" + str + "</p>");                         

        </script>

    </body>

</html>

출력:

지금은 2014년 5월 29일 목요일16시 10분 21초 입니다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

디지털 시계 : 1초마다 refresh 되게

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <meta http-equiv="Refresh" content="1">

        <title> 디지털 시계 </title>

    </head>

    <body>

    <script>

        var now = new Date();

        var str = (now.getHours() > 12) ? (now.getHours() - 12) : now.getHours();

        str = "" + (str.length == 1) ? "0" + str : str;

        str += " : " + ((now.getMinutes().toString().length == 1) ? 

                             "0" + now.getMinutes() : now.getMinutes());

        str += " : " + ((now.getSeconds().toString().length == 1) ? 

                             "0" + now.getSeconds() : now.getSeconds()); 

        document.write("<p style='font-size:3em;font-weight:900'>");

        document.write(str + "</p>");

    </script>

    </body>

</html>

---------------------

디지털 시계 : 1초마다 너무 함수 호출

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <!--<meta http-equiv="Refresh" content="1">-->

        <title> 디지털 시계 </title>

    </head>

    <body>

        <p id="mytime" style='font-size:3em;font-weight:900'></p>

    <script>

        window.addEventListener("load", getTimer, false);

        function getTimer(){

            var now = new Date();

            var str = (now.getHours() > 12) ? (now.getHours() - 12) : now.getHours();

            str = "" + (str.length == 1) ? "0" + str : str;

            str += " : " + ((now.getMinutes().toString().length == 1) ? 

                                 "0" + now.getMinutes() : now.getMinutes());

            str += " : " + ((now.getSeconds().toString().length == 1) ? 

                                 "0" + now.getSeconds() : now.getSeconds()); 

            document.getElementById('mytime').innerHTML = str;

            setTimeout(getTimer, 1000);

        }

        

    </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Math

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Math Object </title>

    </head>

    <body>

        <script>

            var num1 = 123.456;

            var num2 = 345.678;

            var num3 = 567.891;

            document.write("<p>123.456의 반올림값은 " + Math.round(num1) + "</p>");

            document.write("<p>345.678의 절상값은 " + Math.ceil(num2) + "</p>");

            document.write("<p>567.891의 절삭값은 " + Math.floor(num3) + "</p>");

            

            var r = 123;

            function get반지름(radius){

                return Math.floor(Math.pow(radius, 2) * Math.PI);

            }

            document.write("<p>반지름이 " + r + "cm인 원의 넓이는 ");

            document.write(get반지름(r) + "cm<sup>2</sup>입니다.</p>");

        </script>

    </body>

</html>

출력:

123.456의 반올림값은 123


345.678의 절상값은 346


567.891의 절삭값은 567


반지름이 123cm인 원의 넓이는 47529cm2입니다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

=======================================
D-day 계산기
index.html
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <title>우리 자기 기념일 계산기</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/script.js"></script>        
</head>
<body>
    <div id="wrapper">
    <h1>우리 자기 기념일 계산기</h1>
    <form>
        <p id="today"></p>
        <p>우리 자기 처음 만난 날은 :<br>
            <input value="2012" id="meeting_year">년 
            <select id="meeting_month">
                <option value="0">1월</option>
                <option value="1">2월</option>
                <option value="2">3월</option>
                <option value="3">4월</option>
                <option value="4">5월</option>
                <option value="5">6월</option>
                <option value="6">7월</option>
                <option value="7">8월</option>
                <option value="8">9월</option>
                <option value="9">10월</option>
                <option value="10">11월</option>
                <option value="11">12월</option>
            </select>
            <input value="1" id="meeting_day">일
            <input type="button" id="count_btn" value="계산하기">
        </p>
        <p>우리 자기는 오늘 <input id="today_count" disabled> 일 째 입니다.</p>
        <hr>
        <p>우리 자기 <input id="memorial_day"> 일 째 되는 날은?<input type="button" id="memorial_btn" value="계산하기"></p>
        <p>우리 자기의 <input id="memorial_count"> 일 째 되는 날은 <input id="memorial_date"> 입니다.</p>
    </form>
    </div>
</body>
</html>

scripts.js
// 페이지 로딩이 끝나면 init 함수를 콜백
window.addEventListener('load', init, false);

function init() {
// Date 객체 today를 오늘 날짜로 생성
var today = new Date();
// 
var countDayOutput = document.getElementById('today_count');
var memorialCountOutput = document.getElementById('memorial_count');
var memorialDayOutput = document.getElementById('memorial_date');
// 사용자가 입력한 날이 셋팅되었는지에 대한 정보를 저장할 객체 생성
var meetingDay = new Object();
// 오늘 날짜를 id가 today인 단락에 출력
// toLocaleDateString() 메소드를 사용하여 지역 날짜 포맷으로 날짜를 출력 
// 요일은 toWeekDay() 함수를 이용하여 문자열로 반환
document.getElementById('today').innerHTML = "오늘은 " + today.toLocaleDateString() + " " + toWeekDay(today.getDay()) + " 입니다.";
// name이 count_btn인 단추를 클릭하면 todayCounter 함수 콜백
document.getElementById('count_btn').addEventListener('click', todayCounter, false);
// name이 memorial_btn인 단추를 클릭하면 dayCounter 함수 콜백
document.getElementById('memorial_btn').addEventListener('click', dayCounter, false);
// 오늘이 아기 출생일로 부터 몇일 째인가를 구하는 함수
function todayCounter() {
setupBirthday();
// 오늘날짜에 생일 날짜를 뺀다. 날짜의 연산은 밀리초로 결과나 반환된다.
var days = today - meetingDay.date;
// 밀리초로 반환된 값을 날짜로 변환하여 출력
// 값 올림 메소드인 ceil을 적용한 이유는 결과가 12.34 이며 12일과 그 다음날을 살고 있는 것이므로 소수점 이하자리는 올린다..
countDayOutput.value = Math.ceil(days/1000/60/60/24);
}
function dayCounter() {
// 사용자가 입력한 기념일 날짜를 가져온다. 예) 100일
var memorialDay = document.getElementById('memorial_day').value;
// 만일 날짜 객체가 생성되지 않았다면 사용자의 입력 내용으로 날짜 객체를 생성한다.
if (!meetingDay.setted) setupBirthday();
// 계산된 결과 값을 넣을 날짜 객체 생성
var targetDay = new Date();
var theDay = meetingDay.date.getDate();
targetDay.setTime(meetingDay.date.getTime());
targetDay.setDate(theDay + Number(memorialDay) - 1);

memorialCountOutput.value = memorialDay;
// 날짜 객체에 toLocaleDateString()을 적용하면 지역포맷 날짜 문자열로 반환된다.
memorialDayOutput.value = targetDay.toLocaleDateString() + " " + toWeekDay(targetDay.getDay());
}
function setupBirthday() {
// 사용자가 입력한 폼의 값을 변수에 지정
var year = document.getElementById('meeting_year').value;
var month = document.getElementById('meeting_month').value;
var day = document.getElementById('meeting_day').value;
// date 프로퍼티에 날짜 객체를 생성하여 넣는다.
meetingDay.date = new Date(year, month, day);
// 날짜 객체가 생성되었는지를 표시하는 부울 프로퍼티
meetingDay.setted = true;
}
// 날짜 객체의 요일 숫자 코드를 받아서 한글로 반환하는 함수
function toWeekDay(dayNumber) {
   var array = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];
   return array[dayNumber];
}
}

style.css
body {
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
font-size: 0.8em;
}

#wrapper {
width: 400px;
border: 1px solid gray;
margin:auto;
}

p {
text-align: center;
}

h1 {
color: #ffb700;
font-size: 1.8em;
text-align: center;
}

input {
text-align: right;
}

#meeting_year {
width: 50px;
}

#meeting_day {
width: 30px;
}

#today_count {
width: 80px;
}

#memorial_day {
width: 80px;
}

#memorial_count {
width: 40px;
}

#memorial_date {
width: 130px;
}

hr {
border: 0px solid white;
border-top: 1px dashed gray;
width: 300px;
}


+ Recent posts