본문 바로가기

프로그래밍/Javascript

Perfect! Javascript

 01_자바스크립트 개요

자바스크립트 특징

1) 웹브라우저(client-side)에서 구동되는 스크립트 언어(script language)입니다.

2) ECMAScript가 맞는 명칭이지만, 일반적으로 JavaScript로 더 많이 불립니다.

자바스크립트를 사용하는 이유

1) HTML문서에 동적인 기능을 추가합니다.

2) JavaScript는 HTML 문서가 할 수 없는 기능을 지원합니다.

3) JavaScript는 브라우저에서 구동되기 때문에 빠른 성능을 보장합니다.

자바스크립트를 HTML에 작성하는 직접 방법

.another_category { border: 1px solid #E5E5E5; padding: 10px 10px 5px; margin: 10px 0; clear: both; } .another_category h4 { font-size: 12px !important; margin: 0 !important; border-bottom: 1px solid #E5E5E5 !important; padding: 2px 0 6px !important; } .another_category h4 a { font-weight: bold !important; } .another_category table { table-layout: fixed; border-collapse: collapse; width: 100% !important; margin-top: 10px !important; } * html .another_category table { width: auto !important; } *:first-child + html .another_category table { width: auto !important; } .another_category th, .another_category td { padding: 0 0 4px !important; } .another_category th { text-align: left; font-size: 12px !important; font-weight: normal; word-break: break-all; overflow: hidden; line-height: 1.5; } .another_category td { text-align: right; width: 80px; font-size: 11px; } .another_category th a { font-weight: normal; text-decoration: none; border: none !important; } .another_category th a.current { font-weight: bold; text-decoration: none !important; border-bottom: 1px solid !important; } .another_category th span { font-weight: normal; text-decoration: none; font: 10px Tahoma, Sans-serif; border: none !important; } .another_category_color_gray, .another_category_color_gray h4 { border-color: #E5E5E5 !important; } .another_category_color_gray * { color: #909090 !important; } .another_category_color_gray th a.current { border-color: #909090 !important; } .another_category_color_gray h4, .another_category_color_gray h4 a { color: #737373 !important; } .another_category_color_red, .another_category_color_red h4 { border-color: #F6D4D3 !important; } .another_category_color_red * { color: #E86869 !important; } .another_category_color_red th a.current { border-color: #E86869 !important; } .another_category_color_red h4, .another_category_color_red h4 a { color: #ED0908 !important; } .another_category_color_green, .another_category_color_green h4 { border-color: #CCE7C8 !important; } .another_category_color_green * { color: #64C05B !important; } .another_category_color_green th a.current { border-color: #64C05B !important; } .another_category_color_green h4, .another_category_color_green h4 a { color: #3EA731 !important; } .another_category_color_blue, .another_category_color_blue h4 { border-color: #C8DAF2 !important; } .another_category_color_blue * { color: #477FD6 !important; } .another_category_color_blue th a.current { border-color: #477FD6 !important; } .another_category_color_blue h4, .another_category_color_blue h4 a { color: #1960CA !important; } .another_category_color_violet, .another_category_color_violet h4 { border-color: #E1CEEC !important; } .another_category_color_violet * { color: #9D64C5 !important; } .another_category_color_violet th a.current { border-color: #9D64C5 !important; } .another_category_color_violet h4, .another_category_color_violet h4 a { color: #7E2CB5 !important; } \n\n\n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>

<head>

<script type=”text/javascript”>

//자바스크립트 코드

</script>

</head>

</html>

02_데이터타입

어휘 구조

1) 문장 : 세미콜론 (;)으로 문장이 종료됨. 세미콜론없이 문장 줄이 바뀔 시 자동으로 세미콜론 생성됨

2) 주석 : // 한줄 주석 /* */ 여러 줄 주석

기본 데이터 타입

문자열(string), 숫자(number), 불린(boolean)

변수와 상수

1) 변수 : 값의 변경이 가능. var 키워드를 사용하여 선언, 데이터 타입은 명시하지 않음.

2) 상수 : 값을 변경할 수 없음.

타입변환

1) 적합한 데이터 타입이 아닌 데이터가 함수의 매개 인자나 피 연산자로 오는 경우 자동으로 데이터 타입이 변환됨

2) 자동 변환이 불가능한 경우는 오류가 발생

자바스크립트 오류 확인 방법

인터넷 익스플로어의 도구 메뉴 -> 인터넷 옵션 메뉴 -> 고급 탭 -> ‘모든 스크립트 관련 오류 표시’ 체크 박스에 체크 -> 확인 버튼 클릭

실습예제

예제 02-1.html

기본 데이터 타입 형 변환과 '+'연산자를 이용한 문자열 이어붙이기 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var result=(1==2);
        result = result + "script";
        result = result+ 30;
        alert(result);
    </script>
</head>
</html>

예제 결과

예제 02-2.html

parseInt() 함수의 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var price = parseInt("100원짜리 초코우유")*parseInt("3개");
        alert(price);
    </script>
</head>
</html>

예제 결과

03_연산자

연산자에 들어가면서

1) 단항 연산자 : 양수 연산자(-), 음수 연산자(+) 등 피 연산자가 한 개인 연산자

2) 이항 연산자 : 더하기(+), 빼기(-), 곱하기(*), 나누기(/) 등 피 연산자가 두 개인 연산자

3) 삼항 연산자 : (조건: ? ) 등 피 연산자가 세 개인 연산자

산술 연산자

1) 더하기(+) 연산자

피 연사자가 숫자 또는 불린 경우 더하기 연산 / 피 연산자 중 하나라도 문자열이면 문자열 이어 붙이기 연산

2) 빼기(-) 연산자

3) 곱하기(*) 연산자

4) 나누기(/) 연산자

5) 나머지(%) 연산자

6) 단항 마이너스 연산자

7) 단 항 플러스 연산자

8) 증가(++) 연산자 : 전치 증가, 후치 증가 연산자

9) 감소(--) 연산자 : 전치 감소, 후치 감소 연산자

관계 연산자

1) 동등(==) 연산자

두 개의 피 연산자 값을 비교하여 동등하면 true를 반환 데이터 타입을 변환했을 때 같은 값을 가질 수 있으면, 동등

2) 일치(===) 연산자

일치는 데이터 타입도 같고, 데이터도 같으면 true가 반환됨

3)비동등(!=) 연산자

4)불일치(!==) 연산자

5)작음(<) 연산자, 큼(>) 연산자, 작거나 같음(<=) 연산자, 크거나 같음(>=) 등의 비교 연산자

논리 연산자

불린(boolean)연산을 하기 위해 &&, ||, ! 의 논리 연산자

1) &&

피 연산자 모두 true인 경우만 true를 돌려 주고, 그렇지 않으면 false를 돌려 주는 논리 AND(&&) 연산

2) ||

피 연산자 중 하나라도 true이면 true를 돌려 주고, 피 연산자가 모두 false이면 false를 돌려 주는 논리 OR(||) 연산

3) !

피 연산자의 값이 true이면 false를, false이면 true를 돌려주는 논리 NOT(!) 연산

비트 연산자

비트 단위의 연산하기 위해 &, |, ^, ~ 의 비트 연산자

1) & : 비트 AND(&) 연산자

2) | : 비트 OR(|) 연산자

3) ^ : 비트 XOR(^) 연산자

4) ~ : 비트 NOT (~) 연산자

5) >> : 비트 오른쪽 쉬프트(>>) 연산자

6) << : 다음은 비트 왼쪽 쉬프트(<<) 연산자

7) >>> : 오른쪽으로 비트를 이동한 후 오른쪽의 빈 비트들을 무조건 0으로 채움

할당 연산자

1) = : 가장 기본적인 할당 연산자

2) += : 더하기와 할당

3) -= : 빼기와 할당

4) 기타 할당 연산자들 (*=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= )

기타 연산자

1) ? : 연산자

2) typeof 연산자

실습예제

예제 03-1.html

전치 증가 연산자와 후치 증가 연산자에 대한 자바스크립트 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var i=10;
        var result1 = ++i;

        var j=10;
        var result2 = j++;

        alert(result1);
        alert(result2);

    </script>
</head>
</html>

예제 03-2.html

동등 연산자와 일치 연산자에 대한 자바스크립트 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var i = 10;
        var j = "10";

        alert(i==j); // 동등 연산자
        alert(i===j);
    </script>
</head>
</html>

예제 03-3.html

typeof 연산자 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
    
        var data1=90;
        var data2=true;

        var message1 = typeof data1;
        var message2 = typeof datat2;

        alert(message1);
        alert(message2);

    </script>
</head>
</html>

04_의사결정

의사결정 문장에 들어가면서

1) 의사결정 문장의 필요성 : 자바스크립트를 실행할 때 결정되는 조건이나 상황에 따라 어떤 작업을 해야 하는 지 프로그래밍을 해둘 필요가 있음.

2) 의사결정 문장의 종류 : if문, switch문

if문

1)

if( true/false 판별식) {

// 판별식이 true를 돌려주는 경우 if(){ } 안의 내용이

// 모두 실행

}else{ // 판별식이 false를 돌려주는 경우 else{ } 안의 내용이

// 모두 실행

}

2)

if( true/false 판별식) {

// 첫 번째 판별식이 true를 돌려주는 경우 if(){ } 안의 내용이

// 모두 실행

}else if( true/false 판별식) {

// 첫 번째 판별식이 false를 돌려주고

// else if( true/false 판별식)이 ture를 돌려 주면

// 이 블락 안의 모든 문장이 실행

}

3)

if( true/false 판별식) {

// else if는 계속 연결해서 쓸 수 있음

}else if( true/false 판별식) {

}else if( true/false 판별식) {

}else if( true/false 판별식) {

}else{

}

4)

if( true/false 판별식) {

// if안에 또 다른 if문을 쓸 수 있습니다.

if( true/false 판별식) {

}
}

switch 문

1)

switch (변수) {

case 일치 검사할 /변수1 :

//

break ;

case 일치 검사할 /변수2 :

//

break ;

case 일치 검사할 /변수3 :

//

break ;

default :

//

}

실습예제

예제 04-1.html

if~else if 문장을 이용하여 다음 상황을 자바스크립트로 프로그래밍 해보겠습니다.

  • 첫 번째 조건 : 점수(jumsu)가 90점 이상이면 A를 주고,
  • 두 번째 조건 : 그렇지 않고, 점수(jumsu)가 80점 이상이면 B를 주고,
  • 세 번째 조건 : 그렇지 않고, 점수(jumsu)가 70점 이상이면 C를 주고,
  • 네 번째 조건 : 그렇지 않고, 점수(jumsu)가 60점 이상이면 D를 주고,
  • 다섯 번째 조건 : 그 이하는 F를 준다.
if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var jumsu=85;
        if(jumsu>=90){
            alert("A");
        }else if(jumsu>=80){
            alert("B");
        }else if(jumsu>=70){
            alert("C");
        }else if(jumsu>=60){
            alert("D");
        }else{
            alert("F");
        }
    </script>
</head>
</html>

예제 04-2.html

중첩 if문장을 이용하여 다음 상황을 자바스크립트로 작성해보겠습니다.

A: 이번주 로또에 당첨된다면..!!

  • A-1: 상금이 1억이 넘으면 차를 사고 회사를 그만둔다.
  • A-2: 상금이 1억이 넘지 않으면 저금을 한다.

B: 이번주 로또에 당첨되지 않으면 공부를 계속한다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var winlotto = true;
        var prizeMoney = 5000000;
        if(winlotto){
            if(prizeMoney>100000000)
            {
                alert("차를 사고 회사를 그만둔다");
            }else{
                alert("저금을 한다.");
            }
        }else{
            alert("공부를 계속한다.");
        }
    </script>
</head>
</html>

예제 04-3.html

switch 문장에 대한 예제입니다.

다음 상황을 자바스크립트로 프로그래밍해 보겠습니다.

  • 해미 선물은 뿡뿡이
  • 순돌이 선물은 과자
  • 준희 선물은 트랜스포머
  • 철수 선물은 곰 인형
if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var name="순돌";
        var present;

        switch(name){
            case "준희" :
                present="트랜스포머";
                break;
            case "순돌" :
                present="과자"
                break;
            case "순돌" :
                present="곰 인형"
                break;
            case "순돌" :
                present="뿡뿡이"
                break;
        }

        alert(present);
    </script>
</head>
</html>

05_반복

반복 문장에 들어가면서

1) 반복 문장의 필요성 : 같은 작업을 여러 번 반복해야 하는 경우에 반복을 표현하는 문장으로 간편하게 프로그래밍할 수 있음.

2) 반복 문장의 종류 : for문, while문

for문

for( 초기식 ; true/false 판별식 ; 증감식 )
{
//반복해야 하는 문장들
}

while문

1) while문

while(true/false 판별식)
{
//반복해야 하는 문장들
}

2) do while문

do
{
//반복해야 하는 문장들
} while(true/false 판별식)

break/ continue문

1) break : 반복문을 탈출하는 역할

2) continue문 : 현재 반복문을 중지하고 새로운 반복 문을 시작하는 역할

실습예제

예제 05-1.html

for문장과 if문장을 이용하여 10이 소수인지 아닌지를 구하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var num = 10;
        var cnt = 0;
        
        for(var i =2; i<=num; i++){
            if((num%i)==0)cnt++
        }

        if(cnt==1) alert("소수입니다.");
        else if("소수가 아닙니다.");

    </script>
</head>
</html>

예제 05-2.html

중첩 for문장과 if문장을 이용하여 2부터 10까지 수 중 소수를 모두 찾아 출력하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var cnt = 0;
        for(var num=2; num<=10; num++)
        {
            for(var i=2; i<=num; i++)
            {
                if((num%i)==0) cnt++;
            }

            if(cnt==1) document.write(num+"은 소수입니다.<br>");
            else document.write(num + "은 소수가 아닙니다.<br>");
            cnt=0;
        }
    </script>
</head>
</html>

06_배열

배열이 필요한 경우

많은 양의 데이터를 하나의 변수에 저장하여 비슷한 방법으로 처리할 경우 배열을 사용.

1차원 배열

1) 배열 변수 선언

① 배열 크기를 결정하는 배열 변수 선언

예) var myArray = new Array(10); //원하는 크기의 숫자를 괄호 안에 넣음

② 배열 크기를 동적으로 변하게 하는 배열 변수 선언

예) var myArray = new Array();

2) 배열 변수 선언과 함께 초기화

예) var myArray = [ “값1”, “값2“, “값3“, “값4“, “값5“ ] ;

// 값은 문자열인 경우 큰 따옴표(“”)를 사용하고,

// 숫자(number)나 불린(Boolean)경우는 아래와 같이 그대로 사용함

예) var myArray = [ 0,1,2,ture ] ;

3) 배열의 요소에 접근

예)myArray[0] = 100 ;

//배열 변수 이름[인덱스번호]로 배열 요소에 접근

4) 배열의 요소 개수 구하기

예) myArray.length

// 배열 변수 이름.length 변수는 배열의 크기를 저장하고 있음

2차원 배열

1) 2차원 배열 변수 선언과 함께 초기화

var myArray = [ [1,2,3], [4,5,6] ];

2) 2차원 배열 변수 선언

var myArray = new Array(new Array(3), new Array(3));

//또는

var myArray = new Array();

myArray[0] = new Array(3);

myArray[1] = new Array(3);

2) 2차원 배열 변수 사용 예

myArray[0][0] = 100;

myArray[0][1] = 200;

myArray[0][3] = 300;

for in 문

배열의 크기만큼 알아서 반복해주는 for 문장

for(var num in myArray) //myArray.length 즉, 배열 크기 만큼 자동 반복
{
// num 변수는 myArray배열의 요소를 인덱스로 사용할 수 있음
// num 변수는 0부터 자동으로 1씩 증가
}

실습예제

예제 06-1.html

배열 안의 데이터를 올림차순으로 정렬하는 자바스크립트를 작성해 보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var myArray=[199,230,11,2,55,93,23,24,29,1];

        // 작은 수일수록 앞에 오도록 정렬
        for(var i=0; i<myArray.length;i++)
        {
            for(var j=i+1;j<myArray.length;j++)
            {
                if(myArray[i]> myArray[j]){
                    // myArray[i] 값이 myArray[j] 값보다 더 크면
                    // 아래와 같이 두 수를 교환함
                    var temp = myArray[i];
                    myArray[i] = myArray[j];
                    myArray[j] = temp;
                    // myArray[i]에 그 뒤 요소 값들 중 가장 작은 값이 저장됨.
                }
            }
        }

        //정렬 결과를 출력함
        for(var i=0; i<myArray.length; i++)
        {
            document.write(myArray[i]+"<br>");
        }
    </script>
</head>
</html>

예제 06-2.html

2차원 배열의 데이터를 중첩 for in 문장을 이용하여 출력하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var myArray=[[1,2,3],[4,5,6]];

        for(var row in myArray){ //행을 위한 인덱스
            for(var col in myArray[row]){ // 열을 위한 인덱스
                document.write(myArray[row][col]+"");
            }
            document.write("<br>");
        }
    </script>
</head>
</html>

07_함수(1)

함수 정의

1)

var 함수이름 = function() {
//코드
}

2)

function 함수이름() {
//코드
}

매개인자 함수 정의

함수이름() 괄호 안에 매개 인자 개수만큼 매개 변수를 씁니다.

function 함수이름(매개변수1, 매개변수2) {
//코드
}

반환 값이 있는 함수 정의

function 함수이름(매개변수1, 매개변수2) {
//코드
return 반환값;
}

함수 호출

1) 무인자 함수 호출

함수이름();

2) 매개인자가 있는 함수 호출

함수이름(매개인자1, 매개인자2);

3) 매개인자와 반환 값이 있는 함수 호출

var result = 함수이름(매개인자1, 매개인자2);

실습예제

예제 07-1.html

매개인자로 배열을 받아 배열의 원소를 모두 출력해주는 함수 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function arrayPrint(array){
            for(index in array){
                document.write(array[index]+"<br>");
            }
        }

        var jumsu=[100,95,83,94,99,99];
        arrayPrint(jumsu);
    </script>
</head>
</html>

예제 07-2.html

매개인자로 배열을 받아 배열을 정렬해주는 함수입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type='text/javascript'>
        function sortArray(array){
            for(var i=0; i<array.length; i++){
                for(var j=i+1; j<array.length;j++){
                    if(array[i]>array[j]){ // 뒤의 배열 값이 작으면 앞의 값과 교체
                        var temp = array[i];
                        array[i] = array[j];
                        array[j] = temp;
                    }
                }
            }
        }
        function arrayPrint(array){
            for(index in array){
                document.write(array[index]+"<br>");
            }
        }
        var jumsu=[100,95,83,94,99,99];
        sortArray(jumsu); // 배열이 정렬됨
        arrayPrint(jumsu); // 정렬된 배열을 출력
    </script>
</head>
</html>

08_함수(2)

내장함수

1) alert 함수 : 매개인자로 받은 데이터를 경고창에서 보여줍니다.

2) document.write 함수 : 매개인자로 받은 데이터를 웹 브라우저에 출력합니다.

3) confirm 함수 : 매개인자로 받은 데이터를 confirm 창에서 보여주고, 사용자가 ‘확인’ 버튼을 클릭하면 true를, ‘취소’ 버튼을 클릭하면 false를 반환합니다.

4) prompt 함수 : 매개인자로 받은 데이터를 prompt 차에서 보여주고, text box에서 사용자 입력을 받습니다. 사용자가 입력한 값을 반환합니다.

전역변수와 지역변수

1) 전역 변수는 모든 함수에서 공유하는 변수입니다.

2) 지역 변수는 함수 내에서 선언된 변수로 함수 안에서만 사용할 수 있습니다.

실습예제

예제 08-1.html

confirm() 함수를 이용하여 사용자에게 18세 이상인지 물어보고, 18세 이상이면 '터미네이터 상영관으로 입장',

아니면 '텔레토비 상영관으로 입장' 메시지를 웹 브라우저 창에 출력하는 프로그램을 작성해 보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var isAdult = confirm("18세 이상입니까?");
        if(isAdult == true){
            document.write("터미네이터 상영관으로 입장");
        } else {
            document.write("텔레토비 상영관으로 입장");
        }
    </script>
</head>
</html>

18세 이상

=> 확인

18세 이하

=> 취소

예제 08-2.html

prompt() 함수를 이용하여 점수를 3번 입력 받고, 점수의 합과 평균을 구하는 프로그램을 작성해 보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var jumsu = new Array();
        jumsu[0] = prompt("첫번째 점수를 입력하세요.","");
        jumsu[1] = prompt("두번째 점수를 입력하세요.","");
        jumsu[2] = prompt("세번째 점수를 입력하세요.","");
        
        var sum =0;
        for(var index in jumsu)
        {
            sum = sum+parseInt(jumsu[index]);
        }

        alert("점수 합은 "+sum+"평균은 "+ sum/jumsu.length+" 입니다.");
    </script>
</head>
</html>

예제 08-3.html

변수 영역에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var data=100; // 전역 변수 data를 선업하고 100으로 초기화
        function yourJob(){
            data=0; // 전역 변수 data를 사용
        }

        function myJob(){
            var data = 10; // 지역 변수 data를 선언하고 10으로 초기화
            data = data+ 100; // 지역 변수 data를 사용
        }
        
        yourJob(); // 전역변수 data의 값을 0으로 저장
        myJob(); // 전역변수를 사용하지 않음
        alert(data); // 전역변수 data의 값을 읽어 경고창에 보여줌
        // 전역변수 data의 값은 현재 0
    </script>
</head>
</html>

예제 08-4.html

함수를 여러 변수에 저장해보는 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function job(num){
            alert(num+"일 동안 영업 사원이 하는 일을 합시다");
            return ++num;
        }

        var hongGilDongJob = job;
        hongGilDongJob(job(100));
    </script>
</head>
</html>

09_객체지향개념

객체 : 데이터와 메소드들로 구성

객체의 멤버 접근 방법

1) 객체의 메소드 호출 방법 :객체이름.메소드이름()

2) 객체의 프로퍼티 접근 방법 : 객체이름.프로퍼티이름

클래스 프로퍼티 : 해당 클래스에 속하는 모든 객체가 공유하는 값

인스턴스 프로퍼티 : 객체마다 별도의 저장 공간을 가지며, 객체마다 다른 값을 저장할 수 있음

실습예제

예제 09-1.html

배열 객체와 document 객체의 프로퍼티와 메소드를 사용하는 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var data = [10, 20, 30]; // 자바스크립트에서 배열은 자동으로 객체가 됨
        var length = data.length; // 모든 배열객체는 length 라는 인스턴스 프로퍼티가 있음
        document.write(length); // 자바스크립트 인터프린터가 미리 민들어 둔
        // document 내장 객체의 인스턴스 메소드인 write 메소드
    </script>
</head>
</html>

10_이벤트와 이벤트 처리

이벤트 구동 프로그램

이벤트를 감지하고 이벤트 발생 시 그에 대한 이벤트를 처리하는 프로그램을 말합니다.

이벤트 처리기

1) onclick: 클릭 이벤트 처리기

2) ondblclick : 더블클릭 이벤트 처리기

3) onfocus: 포커스를 얻을 때 이벤트 처리기

4) onblur: 포커스를 잃을 때 이벤트 처리기

5) onmousedown: 마우스 버튼을 눌렀을 때 이벤트 처리기

6) onmouseup: 마우스 버튼을 떼었을 때 이벤트 처리기

7) onmousemove : 마우스를 움직였을 때 발생하는 이벤트

8) onmouseout: 마우스를 요소(element)밖으로 움직였을 때 이벤트 처리기

9) onmouseover : 마우스를 요소(element)위로 움직였을 때 이벤트 처리기

10) onkeydown, onkeypress: 키보드 버튼을 눌렀을 때 이벤트 처리기

11) onkeyup: 눌렀던 키보드를 떼어 냈을 때 이벤트 처리기

12) load: 웹 브라우저에 문서가 모두 loading 되었을 때 이벤트 처리기

13) unload: 해당 페이지를 빠져 나갈 때 이벤트 처리기

14) onchange: 사용자의 입력이 변경되었을 때 이벤트 처리기

15) onselect: 텍스트가 선택되었을 때 이벤트 처리기

16) onresize: 창 크기가 변경되었을 때 이벤트 처리기

17) onsubmit : 폼을 제출할 때 이벤트 처리기

18) onreset: 폼을 초기화할 때 이벤트 처리기

19) onabort: 이미지 로딩이 중단될 때 이벤트 처리기

20) onerror: 이미지 로딩 시 에러 이벤트 처리기

실습예제

예제 10-1.html

onchange 이벤트처리기에 대한 예제입니다.

<html>
<body> 정답은 몇 번입니까?
        <select name="answer" onchange="alert('답이 변경됩니다');">
            <option value="1" selected>1번</option>
            <option value="2">2번</option>
            <option value="3">3번</option>
            <option value="4">4번</option>
        </select>
</body>
</html>

예제 10-2.html

onclick 이벤트처리기에 대한 예제입니다.

<html>
<input type="button" name="add" value="클릭!" onclick="alert('클릭 이벤트');"/>
</html>

예제 10-3.html

onload 이벤트 처리기에 대한 예제입니다.

<html>
    <body onload="alert('페이지 로드 완료 이벤트');">
    </body>
</html>

11_DOM(1)

DOM 의 구조

• window 객체 (브라우저)

• location 객체 (URL)

• document 객체 (HTML page)

• anchors 객체 <a>

• body 객체 <body>

• images 객체 <img>

• forms 객체 <form>

• elements객체<input>, <textarea>, <select>

• frames 객체 <frame>

• tables 객체 <table>

• rows 객체 <tr>

• cells 객체<th>, <td>

• title 객체 <title>

window 객체 : 웹 브라우저 창을 표현하는 객체

1) window 객체의 메소드

① window.open() : 웹 브라우저 창을 새로 열어줍니다

② window.close() : 웹 브라우저 창을 닫습니다

document 객체 : HTML 웹 페이지를 표현하는 객체

1) document 의 주요 프로퍼티

① document.bgColor : 웹 페이지의 배경색을 나타냅니다.

② document.title : 웹 페이지의 <title>요소 값을 나타냅니다

③ document.url : 현재 웹 페이지의 주소를

2) document객체를 구성하는 주요 객체들

① document.images : 웹 페이지의 <img>요소들을 표현합니다.

② document.forms : 웹 페이지의 <form>요소들을 표현합니다.

③ document.name속성값 : 해당 name속성값을 갖는 HTML 요소객체를 표현합니다.

실습예제

예제 11-1.html

window 객체에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n 안녕하세요\n \n \n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function newdoc(msg){
            var win = window.open(); // 새 웹 브라우저 창을 열음.
            var doc = win.document;
            // 새 웹 브라우저 창안의 웹 문서객체 주소를 doc 변수가 복사해 감.
            // 즉, doc은 새 웹 브라우저 창 안의 웹 문서
            doc.open(); // doc 객체를 메모리에 생성. 생략가능
            doc.write(msg); // doc 안에 msg를 씀.
            doc.close(); // doc 객체를 메모리에 해제.
        }
    </script>
</head>
<body>
    안녕하세요
    <input type="button" value="새 창/새 문서 열기" onclick="newdoc('Hello New Document');">
    <input type="button" value="창닫기" onclick="window.close();">
</body>
</html>

=> 새 창/새 문서 열기

예제 11-2.html

location 객체에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \nsample\n \n\n
\n \n
\n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function go(){
            alert(document.myform.mypage.value);
            location = document.myform.mypage.value;
        }
    </script>
<title>sample</title>
</head>
<body>
    <form name="myform">
        <select name="mypage" onchange="go();">
            <option selected>Where do you wnat to go?</option>
            <option value="http://www.sdscampus.com">sdscampus homepage</option>
            <option value="http://www.e-campus.co.kr">e-campus homepage</option>
        </select>
    </form>
</body>
</html>

12_DOM(2)

웹페이지 내 요소(element) 찾기

1) document.getElementsByTagName(“HTML태그이름”)

2) document.getElementById(“HTML 요소의 ID 속성 값”)

DOM 트리의 노드 프로퍼티

1) nodeType: 노드의 종류(Element, Text, Attribute 등) 정보를 가지고 있습니다.

2) nodeValue: 노드에 저장된 값으로 Text 노드와 Attribute 노드의 경우에만 이 값이 있습니다.

3) childNodes: 하나의 노드의 모든 하위 노드를 저장하고 있는 배열입니다.

4) firstChild: 하나의 노드의 하위 노드 중 첫 번째 하위 노드를 저장합니다.

5) lastChild: 하나의 노드의 하위 노드 중 마자막 노드를 저장합니다.

웹페이지 수정하기

1) removeChild(), createTextNode(), appendChild() 메소드를 이용한 웹 페이지 내용 수정이 가능합니다.

2) nodeValue프로퍼티 이용한 웹 페이지 내용 수정이 가능합니다.

3) innerHTML프로퍼티 이용한 웹 페이지 내용 수정이 가능합니다.

웹페이지 속성 확인과 수정하기

1) getAttribute(“속성이름”) : 노드의 속성을 값을 얻을 수 있습니다.

2) setAttribute(“속성이름”,”새로운 속성값”) : 노드의 속성 값을 수정할 수 있습니다.

실습예제

예제 12-1.html

nodeValue 프로퍼티를 이용하여 텍스트를 추가하는 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n

\n 텍스트가 추가됩니다.\n

\n \n \n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function changeText(){
            var newmsg = document.getElementById('letter').firstChild.nodeValue + document.getElementById('comment').value;
            document.getElementById('letter').firstChild.nodeValue=newmsg;          
        }
    </script>
</head>
<body>
    <p id="letter">
    텍스트가 추가됩니다.
    </p>
    <input type="text" id="comment"/>
    <input type="button" onclick="changeText();" value="등록"/>
</body>
</html>

예제 12-2.html

childNodes, nodeType, nodeValue 프로퍼티를 이용한 HTML 웹 페이지의 text 확인 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n
\n 첫번째 메세지입니다. 저를 찾아 보세요.
\n
\n 두번째 메세지입니다. 저를 찾아 보세요.\n
\n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function searchFormText(){
            var elementCnt = 0;
            var loginform = document.getElementById("loginform").childNodes;

            for(var index=0; index<loginform.length; index++){
                if(loginform[index].nodeType==3){
                    // nodeType이 3이면, 즉, 텍스트이면
                    // 아래와 같이 그 텍스트 값을 경고창에 보여줌
                    alert(loginform[index].nodeValue);
                }
            }
        }
    
    </script>
</head>
<body>
    <form id="loginform">
        첫번째 메세지입니다. 저를 찾아 보세요.<br>
        <input id="ok" type="button" value="form의 Text 순회" onclick="searchFormText();"/><br>
        두번째 메세지입니다. 저를 찾아 보세요.
    </form>
</body>
</html>

13_내장객체

값타입 변수와 참조 타입 변수

1) 값타입 변수 : 변수 자신의 메모리 영역에 값을 저장

2) 참조 타입 변수 : 변수 자신의 메모리 영역에값이 저장된 곳의 주소를 저장 객체의 변수는 무조건 참조 타입 변수

String객체 문자열을 가지고 있는 객체

1) length: 문자열의 길이 정보를 가지고 있는 프로퍼티

2) charAt(): 매개인자로 들어온 숫자에 해당되는 인덱스의한 문자를 추출하여 반환

3) substring(): 현재 문자열의 일부 문자열을 반환

4) indexOf(): 매개 인자로 받은 문자열을 현재 문자열에서 찾아 인덱스 반환

Date 객체

특정 순간의 날짜와 시간 정보를 가지고 있는 객체

1) new Date(), new Date(“년도/월/일”), new Date(년도,월,일)

2) getFullYear(), getMonth(), getDate(), getDay() : 년도, 월, 날짜, 요일 정보를 얻을 수 있는 메소드

3) setYear(년도), setMonth(월), setDate(일) : 년도, 월, 날짜, 요일 정보를 변경할 수 있는 메소드

배열 객체

배열을 저장하는 객체

1) length : 배열의 요소 수를 반환

2) toString(): 배열 안의 요소를 모두 문자열로 반환

3) join(): 매개인자로 받은 구분자를 이용하여 배열 안의 요소를 모두 문자열로 반환

4) sort(): 배열 안의 요소를 정렬하여 반환

5) reverse() : 배열 안의 원소를 반대로 바꾼 후 반환

6) concat(): 원래의 배열이 이어 붙이기를 하여 반환

7) slice() : 배열의 일부분을 잘라서 반환

Math객체

수학적인 메소드, 상수 정보를 저장하고 있음.

1) Math.PI: 수학의 PI(3.14) 값을 가지고 있는 상수

2) Math.round() : 매개 인자로 들어온 실수를 정수로 반올림하여 반환

3) Math.floor() : 매개 인자로 들어온 실수보다 작은 정수로

4) Math.ceil (): 매개 인자로 들어온 실수보다 큰 정수로 반올림하여 반환

5) Math.random () : 0에서 1사이의 난수를 발생시켜 반환

실습예제

예제 13-1.html

String 객체의 메소드에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var name = new String("javascript");
        document.writeln('사용할 String: <br>'+name);
        document.writeln('<br>문자열 길이: <br>'+name.length); // 문자열 길이
        document.writeln('<br>'+'2번 인덱스의 문자: <br>'+name.charAt(2)); // 2번 인덱스의 문자
        document.writeln('<br>'+'현재 문자열에서 [script] 문자열의 위치: <br>'+name.indexOf('script')); // 현재 문자열에서 'script' 문자열의 위치
        document.writeln('<br>'+'현재 문자열에서 [test] 문자열의 위치: <br>'+name.indexOf('test')); // 현재 문자열에서 'test' 문자열의 위치
        document.writeln('<br>'+'현재 문자열에서 2번 인덱스 문자부터 4번 인덱스 문자 바로 앞까지 문자열: <br>'+name.substring(2,4)); // 현재 문자열에서 2번 인덱스 문자부터 4번 인덱스 문자 바로 앞까지 문자열
    </script>
</head>
</html>

예제 13-2.html

배열객체의 메소드에 대한 예제입니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        function modifyArry(array){
            array = array.sort(); // 배열을 정렬하여 반환
            array = array.concat('tail'); // 배열의 끝에 'tail'을 연결하여 반환
            return array;
        }

        var data = new Array();
        data[0] = 'a';
        data[1] = 'c';
        data[2] = 'cc';
        data[3] = 'ab';
        data[4] = 'abc';

        data = modifyArry(data);
        alert("배열의 데이터는"+ data.join(" 와"));

    </script>
</head>
</html>

14_폼과 폼엘리먼트

Form 객체

5) document.forms : HTML form 요소의 배열을 저장

6) onsubmit: submit 버튼이 클릭될 때 발생되는 이벤트처리기

7) onreset : reset 버튼이 클릭될 때 발생되는 이벤트처리기

Form Elements

1) elements: Form내 HTML 요소와 매핑되는 객체의 배열을 저장

2) Form내모든 HTML 요소 객체의 프로퍼티.

①type : 요소의 type 속성 값 정보

②name : 요소의 name 속성 값 정보

③value : 요소의 value 속성 값 정보

3) checkbox와 radio 요소 객체의 프로퍼티

checked : 사용자가 체크하면 ture, 체크하지 않았으면 false

4) Text field 요소 객체의 프로퍼티 value 프로퍼티로 사용자가 입력한 값을 확인하여 유효성 검증을 할 수 있음.

5) select 요소 객체의 프로퍼티

①selectedIndex : 선택된 option의 인덱스 값 정보를 저장

②options : select 요소의 모든 option객체를 가진 배열 객체

③동적으로 option을 생성하는 방법

option 객체를 다음과 같이 생성하고, select 객체의 options 프로퍼티의 값으로 새로 생성한 option 객체를 할당

예)

var colors = new Option(“red”,”red”, false, false);

document.selectColor.color.options[0] = colors;

실습예제

예제 14-1.html

<select>요소 객체의 selectedIndex프로퍼티를 이용하여 사용자가 선택한 option 값을 알아내는 프로그램을 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\n \n
\n 목적지를 선택하세요.\n \n

\n

\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

    function check(){
        var idx=document.answer1.color.selectedIndex;
        confirm(document.answer1.color.options[idx].value+'를 선택하였습니다 맞으면 확인을 클릭하세요.');
    }

</script>
</head>
<form name='answer1' action='nextpage'>
    목적지를 선택하세요.
    <select name='color' onchange="check();">
        <option value='Sydney'/>Sydney
        <option value="LA"/>LA
    </select>
    <p>
</form>
</html>

예제 14-2.html

필수 입력 항목을 검증하는 프로그램을 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\n \n\n
\n 이름을 입력하세요 :
\n
\n 주소를 입력하세요 :
\n
\n 아이디를 입력하세요 :
\n
\n 패스워드를 입력하세요 :
\n
\n \n
\n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

    function check(){
        var elm = document.joinForm.elements;
        for(var index=0 ; index < elm.length ; index++){
            if (elm[index].value.length==0){
                alert(elm[index].name+ ' 항목을 입력하여야 합니다');
                elm[index].style.borderColor="#FF0000";
                elm[index].focus();
                return false;
            }
        }
    }

</script>
</head>
<body>
    <form name="joinForm" action="nextpage" onsubmit="return check();">
        이름을 입력하세요 : <br>
        <input type="text" name="name"><br>
        주소를 입력하세요 : <br>
        <input type="text" name="adress"><br>
        아이디를 입력하세요 : <br>        
        <input type="text" name="id"><br>
        패스워드를 입력하세요 : <br>
        <input type="password" name="pw"><br>
        <input type="submit">
    </form>
</body>
</html>

15_유효성 검증

필수입력 필드 검증

6) Text Field의 경우 : length 프로퍼티 값의 문자열의 길이를 확인

7) checkbox나 radio의 경우 : checked 프로퍼티 값이 true인 것이 있는지 확인

8) select의 경우 : selectedIndex 프로퍼티 값을 확인

숫자입력 검증

isNaN() 함수이용

입력 문자열의 최대 길이/최소 길이 검증

length 프로퍼티 값의 문자열의 길이를 확인

문자열 패턴 검증

문자열의 chatAt() 함수를 이용하여 문자열의 문자를 하나씩 확인 정규 표현식 이용 가능

innerHTML을 이 용한 경고 메시지는 alert()를 대신할 수 있음

실습예제

예제 15-1.html

숫자를 검증한 후, 경고창과 innerHTML을 이용한 경고 메시지를 출력하는 프로그램을 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\n \n
\n

전화번호를 입력하세요 :\n

* -\n * -\n *\n

\n \n
\n

\n

\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

    function validate(){
        if(validateNotEmpty(document.joinForm.area)==false) return false;
        else if(validateNotEmpty(document.joinForm.pre)==false) return false;
        else if(validateNotEmpty(document.joinForm.last)==false) return false;
        else return true;
    }

    function validateNotEmpty(element){
        if(element.value.length==0){
            document.getElementById('message').innerHTML = "<font color='red'>*표시는 필수 입력 항목입니다.</font>";
            element.style.borderColor="#FF0000";
            element.focus();
            return false;
        }else{
            document.getElementById('message').innerHTML="";
            element.style.borderColor="#ffffff";
            return true;
        }
    }

    function validateNumber(numberElement){
        // 숫자가 아니면 isNaN()이 true를 반환하여 다음 실행.
        if(isNaN(numberElement.value)) {
            alert('전화번호는 숫자만 입력해야 합니다.');
            numberElement.style.borderColor="#FF0000";
            numberElement.focus();
            return false;
        } else return true;
    }


</script>
</head>
<form name="joinForm" action="join" onsubmit="return validate();">
    <p>전화번호를 입력하세요 :
        <p> *<input type="text" name="area" size="3" maxlength="3" onblur="validateNumber(this);"> -
            *<input type="text" name="pre" size="4" maxlength="4" onblur="validateNumber(this);"> -
            *<input type="text" name="last" size="4" maxlength="4" onblur="validateNumber(this);">
    </p>
    <input type="submit" value="join"/>
</form>
<p id="message">
</p>
</html>

16_정규식

정규표현식이란?

1) 정규표현식 : 문자 패턴을 정의할 수 있는 식

2) RegExp 객체의 test() 메소드를 이용하여 정규표현식과 문자열 패턴 일치 검증

정규표현식 메타문자

1) […] : 대괄호([]) 안에 있는 문자 중에 하나라도 존재하면 패턴이 일치

2) [^…]: 대괄호([]) 안에 없는 문자가 하나라도 존재하면 패턴이 일치

3) . : newline외에 어떤 문자라도 존재하면 패턴이 일치.

4) ₩d : 숫자에 해당되는 문자가 하나라도 존재하면 패턴이 일치.

5) ₩w : 문자나 숫자에 해당되는 문자가 하나라도 존재하면 패턴이 일치

6) ₩s : 공백에 해당되는 문자가 하나라도 존재하면 패턴이 일치

정규표현식 패턴의 시작과 끝

1) ^ : 문자열의 시작 부분을 나타냄

2) $ : 문자열의 끝 부분을 나타냄

정규표현식 수량한정자

1) {n} : 바로 앞의 패턴이 정확히 n번 나타나면 패턴이 일치

2) {n,m} : 바로 앞의 패턴이 최소 n번, 최대 m번 나타나면 패턴이 일치

3) * : 바로 앞의 패턴이 0번 또는 그 이상 나타나면 패턴이 일치

4) + : 바로 앞의 패턴이 1번 또는 그 이상 나타나면 패턴이 일치

5) ? : 앞의 패턴이 0번 또는 1번 나타나면 패턴이 일치

실습예제

예제 16-1.html

이메일 입력의 유효성을 검증하는 프로그램을 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\nsample\n \n\n 이메일을 입력하세요\n \n

\n\n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">
function checkEmail(){
    var emailPattern=/^\w+@\w+\.\w+$/;
    var inputText = document.getElementById("email").value;
    var message="";

    if(emailPattern.test(inputText)){
        message="이메일 입력 형식에 맞게 작성되었습니다.";
    }else{
        message="<font color='red'> 이메일 입력 형식이 잘못되었습니다."+"</font>";
    }

    document.getElementById("message").innerHTML=message;
}
</script>
<title>sample</title>
</head>
<body>
    이메일을 입력하세요
    <input id="email" type="text" onchange="checkEmail();"/>
    <p id="message"></p>
</body>
</html>

17_사용자 정의 객체(1)

사용자 정의 객체 생성 방법

1) 사용자 정의 객체의 생성자 정의: 함수 정의와 같은 방법으로 정의. 반환 값이 없음.

2) 사용자 정의 객체 생성 : new 연산자와 함께 생성자 함수 호출

예) new Car(); new Person();

사용자 정의 객체의 인스턴스 프로퍼티

1) 인스턴스 프로퍼티 정의 : 생성자 함수 안에서 this를 사용한 변수로 정의

2) 인스턴스 프로퍼티 사용 : 객체이름.프로퍼티이름

예) one.id = 10 ; two.id=20 ;

사용자 정의 객체의 인스턴스 메소드

1) 인스턴스 메소드 정의 : 생성자 안에서 this를 사용한 변수에 함수를 정의

2) 인스턴스 메소드 호출 : 객체이름.인스턴스메소드이름() ;

prototype

1) prototype이란? : 클래스가 가지고 있어야 하는 정보

2) prototype 접근 방법 : 생성자함수이름.prototype

예) Array.prototype String.protytype

3) protytype를 이용한 인스턴스 메소드의 중복 제거 / 생성자 함수의 prototype객체에 인스턴스 메소드를 정의

프로퍼티의 열거, 확인, 삭제

1) 사용자 정의 프로퍼티의 열거 : for in 문장을 이용

2) 프로퍼티 확인 : in 연산자를 이용

3) 프로퍼티 삭제 : delete 연산자를 이용

읽기 전용 프로퍼티 생성 방법

매개인자로 받은 값을 인스턴스 프로퍼티로 저장하지 않음 / 읽어 볼 수만 있는 메소드 정의

실습예제

예제 17-1.html

사용자 정의 객체를 위한 생성자 함수를 작성하고, 사용자 정의 프로퍼티를 열거하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\nsample\n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

var Circle=function(radius){
    this.radius=radius;
}

Circle.prototype.draw=function(){
    alert("반지름이"+this.radius+"인 원 그림");
}

var one = new Circle(10);
one.draw();

var propertyName="";
for(var name in one){
    propertyName=propertyName+""+name;
}

alert(propertyName);

</script>
<title>sample</title>
</head>
</html>

예제 17-2.html

사용자 정의 객체를 위한 생성자 함수를 작성하고, 사용자 정의 객체를 사용하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \nsample \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

    var Car = function(id){
        this.id = id;
        this.speed = 0;
        this.engine = false;
    }

    Car.prototype.startEngine=function(){
        this.engine=true;
    }

    Car.prototype.stopEngine=function(){
        this.speed =0;
        this.engine=false;
    }

    Car.prototype.upSpeed=function(speed){
        this.speed=this.speed+speed;
    }

    Car.prototype.downSpeed=function(speed){
        var nowSpeed = this.speed-speed;
        if(nowSpeed>=0)
        {
            this.speed=nowSpeed;
        }
    }

    Car.prototype.run=function(){
        if(this.engine){
            alert(this.id+"번 자동차는"+this.speed+"속도로 달림");
        }else{
            alert(this.id+"번 자동차는 engine에 시동부터 걸어야 합니다.");
        }
    }

    var mycar = new Car(1);
    var yourcar = new Car(2);
    mycar.startEngine();
    mycar.upSpeed(100);
    mycar.run();
    yourcar.run();

</script>  
<title>sample</title>  
</head>
</html>

18_사용자 정의 객체(2)

클래스 프로퍼티

1) 클래스 프로퍼티 특징 : 객체가 공유하는 값 저장

2) 클래스 프로퍼티 정의 : 클래스이름.prototype.프로퍼티이름

클래스 메소드

1) 클래스 메소드의 특징 : 인스턴스 프로퍼티 사용 못함

2) 클래스 메소드의 정의 : 클래스이름.클래스메소드이름 = function(){…}

3) 클래스 메소드를 호출 : 클래스이름.클래스메소드이름()

상속

1) 상속 특징 : 상위 클래스의 프로퍼티와 메소드를 하위 객체에서 재사용

2) 상속 방법 : 하위 클래스의 prototype 객체로 상위 객체 설정.

3) 메소드 재정의 : 상위 클래스에서 상속받은 메소드를 하위 클래스에서 다시 정의 가능함

Object 클래스

1) constructor : 객체의 생성자 정보를 갖는 프로퍼티

2) toString() : 객체의 정보를 문자열로 반환하는 메소드

3) valueOf () : 객체의 정보를 기본 데이터 타입 / (숫자 또는 불린)으로 반환하는 메소드

instanceof

객체가 특정 클래스 타입인지 확인해 주는 연산자

실습예제

예제 18-1.html

클래스 프로퍼티와 클래스 메소드를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

var Student = function(id){
    this.id = id;
    Student.prototype.totalCnt=Student.prototype.totalCnt+ 1;
}

Student.prototype.totalCnt = 0; // 클래스 프로퍼티

Student.getTotalCnt = function(){ // 클래스 메소드
    return Student.prototype.totalCnt;
}

var one = new Student(10);
var two = new Student(20);

alert(Student.getTotalCnt());

</script>
</head>
</html>

예제 18-2.html

prototype을 이용하여 상속하는 자바스크립트를 작성해보겠습니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n\nsample\n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
<script type="text/javascript">

var Student=function(id){
    this.id = id;
}

Student.prototype.getId=function(){
    return this.id;
}

var VIPStudent=function(id){
    this.id = id;
}
VIPStudent.prototype=new Student();

var one = new VIPStudent(10);
alert(one.getId());

</script>
<title>sample</title>
</head>
</html>

19_브라우저 창 조작

타이머

3) setTimeout() : 일정한 시간이 지나면, 특정 작업을 자동으로 실행

4) clearTimeout() : setTimeout()으로 설정한 것을 취소

5) setInterval(): 설정된 시간 간격마다, 반복해서 실행

6) clearInterval() : setInterval()으로 설정한 것을 취소

Location과 History

1) Location 객체

① href : 웹 브라우저 창 문서의 URL

② reload() : 현재 페이지를 다시 불러오는 메소드

③ replace() : 매개 인자로 들어온 URL을 현재 웹 브라우저 창에 불러오는 메소드

2) History 객체

① back() : 열어본 페이지 목록의 한 단계 “뒤로 이동”

② forward() : 열어본 페이지 목록의 한 단계 “앞으로 이동”

③ go() : 매개인자로 받은 값이 음수라면 그 절대값 만큼 뒤로 이동하고 양수라면 앞으로 이동

화면과 브라우저 정보

1) Screen 객체

① width와 height : 클라이언트 디스플레이 크기

② availWidth와 availHeight : 실제로 사용할 수 있는 클라이언트의 디스플레이 크기

2) Navigator 객체

웹 브라우저의 전반에 대한 정보

① appName : 웹 브라우저의 이름

② appVersion : 웹 브라우저의 버전 정보

창 조작

1) Window 객체

① open()/close() : 웹 브라우저 새 창의 열기와 닫기

② moveTo()/moveBy() : 웹 브라우저 창의 이동

③ resizeTo()/resizeBy() : 웹 브라우저 창 크기 변경

④ scrollTo()/scrollBy() : 웹 브라우저 스크롤

⑤ focus()/blur() : 웹 브라우저 창의 포커스를 획득/잃음

다중 창 조절

1) frames 객체 : 프레임을 표현하는 객체 배열

실습예제

예제 19-1.html

1초 후에 오늘의 날짜 정보 경고창을 띄우는 자바스크립트를 작성합니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        var reservedcode = "var day = new Date();" + "var info = day.getFullYear()+'/'+"+"day.getMonth()+1+'/'+day.getDate();"+"alert(info);";
        setTimeout(reservedcode,1000);
    </script>
</head>
</html>

예제 19-2.html

1초 후에 좌측 상단으로 현재 웹 브라우저 창을 이동하고, 그 후 1초 뒤 http://www.e-camus.co.kr 로 웹 페이지의 URL을 변경하는 자바스크립트를 작성합니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n sample\n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
<head>
    <script type="text/javascript">
        setTimeout("moveTo(0,0);",1000);
        setTimeout("location.href='http://www.credu.co.kr';",2000);
    </script>
    <title>sample</title>
</head>
</html>

20_쿠키

쿠키 개념

1) 쿠키 필요성 : 사용자 별로 사용자의 데이터를 유지할 필요가 있을 때 쿠키 사용

2) 쿠키의 문제점

보안상의 문제 때문에 중요한 정보는 저장하면 안됨.

쿠키 저장 방법

1) 쿠키 저장 방법

document.cookie = “쿠키이름=쿠키값” +”; 쿠키속성이름=쿠키속성값”

2) 쿠키의 속성

① expires : 만료 날짜

② max-age : 쿠키 유효기간

③ path : 쿠키 데이터를 읽을 수 있는 경로

④ domain : 쿠키 데이터를 읽을 수 있는 도메인

⑤ secure : 보안 프로토콜을 사용할 경우만 쿠키를 이용할 수 있게 설정

쿠키 읽는 방법

document.cookie 프로퍼티 값을 읽고 indexOf() 함수나 substring() 함수를 이용하여 필요한 쿠키 값을 얻음.

쿠키 값의 인코딩/디코딩

쿠키 문자열이 세미콜론, 쉼표, 공백문자를 포함해야 할 경우는 다음과 같은 함수로 인코딩, 디코딩 함.

1) encodeURIComponent() 함수 : 쿠키 값 인코딩

2) decodeURIComponent() 함수 : 쿠키 값 디코딩

실습예제

예제 20-1.html

...

21_자바스크립트와 HTTP XML

자바스크립트와 HTTP

1) 자바스크립트에서 HTTP 요청이 일어나게 하는 법

① location 객체의 이용

location.href = 요청할 url;

② form 객체의 submit() 메소드 호출

③ XMLHttpRequest 객체 이용하는 법

2) XMLHttpRequest이용하여 HTTP 요청이 일어나게 하는 법

① XMLHttpRequest 객체 생성하기

var request = new XMLHttpRequest();

② Http 요청을 만들어 낸 후 웹 서버에 제출

request.open(GET, url, false);
request.send(null);

③ HTTP 요청에 대한 응답 받기

request.responseText

자바스크립트와 XML

1) XML에 대한 소개

구조와 내용, 표현이 분리하여 데이터를 저장

2) XMLHttpRequest객체를 이용한 HTTP 요청과, XML 문서 확인, XML 문서 얻기

var request = new XMLHttpRequest();
//.. 중략
if (request.status == 200){
if (request.getResponseHeader(Content-Type) == text/xml){
var doc = request.responseXML;
// xml 문서를 사용
}
}

동적 데이터에 대한 로딩과 저장

1) XMLHttpRequest 객체를 이용한 비 동기적 데이터 로딩

① XMLHttpRequest 객체 생성하기

var request = new XMLHttpRequest();

② Http 요청을 만들어 낸 후 웹 서버에 제출

request.open(GET, url, true); //동기방법과 다른 점은
//open 메소드의 세번째 매개인자가 true인 것
request.send(null);

③ 콜백 함수 작성

request.onreadystatechange = test ; // test라는 함수를 이벤트처리기에 등록
// 응답이 완료되면 test 함수 자동 실행
function test(){ // 요청에 대한 응답이 완료되어 request 객체의 상태가 바뀌면
// 자동으로 실행될 함수
// 이 함수 안에서 응답 받은 데이터를 이용하면 됨
}

실습예제

예제 21-1.html

XMLHttpRequeset 객체를 이용하여 동기적으로 HTTP 요청을 하는 자바스크립트를 작성합니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
    <head>
        <script type="text/javascript">

            var request = new XMLHttpRequest(); // XMLHttpRequeset 객체를 작성합니다.
            request.open("GET", "http://www.credu.com", false);
            // XMLHttpRequest객체의 GET방식으로 사이트를 동기적으로 요청하는 open 메소드를 작성합니다.
            request.send(null);
            // XMLHttpRequest객체의 send 메소드를 작성합니다.
            if(request.status == 200){
                alert(request.responseText);
            }else{
                alert(request.status+""+request.statusText)
            }

        </script>
    </head>
</html>

예제 21-2.html

XMLHttpRequest 객체를 이용하여 비동기적으로 HTTP 요청을 하는 자바스크립트를 작성합니다.

if (!window.T) { window.T = {} } window.T.config = {"TOP_SSL_URL":"https://www.tistory.com","PREVIEW":false,"ROLE":"guest","PREV_PAGE":"","NEXT_PAGE":"","BLOG":{"id":2859442,"name":"hihellloitland","title":"27","isDormancy":false,"nickName":"hihelllo","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":false,"COMMENT_LOGIN_CONFIRM_MESSAGE":"","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://hihellloitland.tistory.com/31","DEFAULT_URL":"https://hihellloitland.tistory.com","USER":{"name":null,"homepage":null,"id":0,"profileImage":null},"SUBSCRIPTION":{"status":"none","isConnected":false,"isPending":false,"isWait":false,"isProcessing":false,"isNone":true},"IS_LOGIN":false,"HAS_BLOG":false,"IS_SUPPORT":false,"IS_SCRAPABLE":false,"TOP_URL":"http://www.tistory.com","JOIN_URL":"https://www.tistory.com/member/join","PHASE":"prod","ROLE_GROUP":"visitor"}; window.T.entryInfo = {"entryId":31,"isAuthor":false,"categoryId":766226,"categoryLabel":"프로그래밍/Javascript"}; window.appInfo = {"domain":"tistory.com","topUrl":"https://www.tistory.com","loginUrl":"https://www.tistory.com/auth/login","logoutUrl":"https://www.tistory.com/auth/logout"}; window.initData = {}; window.TistoryBlog = { basePath: "", url: "https://hihellloitland.tistory.com", tistoryUrl: "https://hihellloitland.tistory.com", manageUrl: "https://hihellloitland.tistory.com/manage", token: "t5aXiNM7S06QfGSqWxF+NpQataWzMi6zilOjK3ZH9dsZ7Uuk4yla2hl5FQ4HaI+E" }; var servicePath = ""; var blogURL = ""; \n \n \n\n"}}" data-ve-attributes="{"typeof":"mw:Extension/syntaxhighlight","about":"#mwt3"}">
<html>
    <head>
        <script type="text/javascript">
            var request = new XMLHttpRequest();
            request.open("GET", "http://www.e-campus.co.kr/index.jsp", true);
            request.send(null);

            request.onreadystatechange = test;

            function test(){
                document.write("응답완료");
            }
        </script>
    </head>
</html>


'프로그래밍 > Javascript' 카테고리의 다른 글

05_반복  (0) 2018.02.27
04_의사결정  (0) 2018.02.27
03_연산자  (0) 2018.02.27
02_데이터타입  (0) 2018.02.27
01_자바스크립트 개요  (0) 2018.02.27