[ 자바스크립트로 사용자 OS 버전 확인하는 코드(IE버전 X 운영체제 판별)]


자바스크립트로 IE8 과 같은 브라우저 버전 체크하는 코드는 많은데 막상 사용자의 운영체제가 무슨 버전인지까진 판별하는 코드가 잘 없었는데


다른분 티스토리에서 보고 유용한거같아 공유하려합니다.


조금더 덧대서 해당 윈도우 운영체제에 로그인한 사용자명의 폴더를 알아야할 경우


var net = new ActiveXObject ( "WScript.NetWork" );

var userName = net.UserName;

strFilePath = "C:\\Users\\" + userName + "\\AppData\\Local\\" + nanumTechnologiesPath; 코드를 사용하시면 로그인한 userName도 얻어올 수 있습니다.


이 아래는 자바스크립트로 운영체제 종류와 버전을 판별하는 코드입니다.


// JavaScript Document

// 만든이 : 다섯방울, THREE™ (http://the3.tistory.com)

// 주소 : http://the3.tistory.com/17

// Data : 2015. 01. 28

// Version : 0.2

// 참조 http://www.openspc2.org/userAgent/

// OS 버전 보기


var uanaVigatorOs = navigator.userAgent;

var AgentUserOs= uanaVigatorOs.replace(/ /g,'');

var Ostxt="";

var OSName="";

var OsVers="";


// This script sets OSName variable as follows:

// "Windows"    for all versions of Windows

// "MacOS"      for all versions of Macintosh OS

// "Linux"      for all versions of Linux

// "UNIX"       for all other UNIX flavors 

// "Unknown OS" indicates failure to detect the OS


new function() {

    var OsNo = navigator.userAgent.toLowerCase(); 


    jQuery.os = {

        Linux: /linux/.test(OsNo),

        Unix: /x11/.test(OsNo),

        Mac: /mac/.test(OsNo),

        Windows: /win/.test(OsNo)

    }

}


function OSInfoDev(){

if($.os.Windows) {

if(AgentUserOs.indexOf("WindowsCE") != -1) OSName="Windows CE";

else if(AgentUserOs.indexOf("Windows95") != -1) OSName="Windows 95";

else if(AgentUserOs.indexOf("Windows98") != -1) {

if (AgentUserOs.indexOf("Win9x4.90") != -1) OSName="Windows Millennium Edition (Windows Me)" 

else OSName="Windows 98"; 

}

else if(AgentUserOs.indexOf("WindowsNT4.0") != -1) OSName="Microsoft Windows NT 4.0";

else if(AgentUserOs.indexOf("WindowsNT5.0") != -1) OSName="Windows 2000";

else if(AgentUserOs.indexOf("WindowsNT5.01") != -1) OSName="Windows 2000, Service Pack 1 (SP1)";

else if(AgentUserOs.indexOf("WindowsNT5.1") != -1) OSName="Windows XP";

else if(AgentUserOs.indexOf("WindowsNT5.2") != -1) OSName="Windows 2003";

else if(AgentUserOs.indexOf("WindowsNT6.0") != -1) OSName="Windows Vista/Server 2008";

else if(AgentUserOs.indexOf("WindowsNT6.1") != -1) OSName="Windows 7";

else if(AgentUserOs.indexOf("WindowsNT6.2") != -1) OSName="Windows 8";

else if(AgentUserOs.indexOf("WindowsNT6.3") != -1) OSName="Windows 8.1";

else if(AgentUserOs.indexOf("WindowsNT6.4") != -1) OSName="Windows 10";

else if(AgentUserOs.indexOf("WindowsPhone8.0") != -1) OSName="Windows Phone 8.0";

else if(AgentUserOs.indexOf("WindowsPhoneOS7.5") != -1) OSName="Windows Phone OS 7.5";

else if(AgentUserOs.indexOf("Xbox") != -1) OSName="Xbox 360";

else if(AgentUserOs.indexOf("XboxOne") != -1) OSName="Xbox One";

else if(AgentUserOs.indexOf("Win16") != -1) OSName="Windows 3.x";

else if(AgentUserOs.indexOf("ARM") != -1) OSName="Windows RT";

else OSName="Windows (Unknown)";

if(AgentUserOs.indexOf("WOW64") != -1) OsVers=", WOW64";

else if(AgentUserOs.indexOf("Win64;x64;") != -1) OsVers=", Win64 on x64";

else if(AgentUserOs.indexOf("Win16") != -1) OsVers=" 16-bit";

else OsVers=" on x86";

} else if ($.os.Linux) {

if(AgentUserOs.indexOf("Android") != -1) { OSName = getAndroidDevName(); }

else if(AgentUserOs.indexOf("BlackBerry9000") != -1) OSName="BlackBerry9000";

else if(AgentUserOs.indexOf("BlackBerry9300") != -1) OSName="BlackBerry9300";

else if(AgentUserOs.indexOf("BlackBerry9700") != -1) OSName="BlackBerry9700";

else if(AgentUserOs.indexOf("BlackBerry9780") != -1) OSName="BlackBerry9780";

else if(AgentUserOs.indexOf("BlackBerry9900") != -1) OSName="BlackBerry9900";

else if(AgentUserOs.indexOf("BlackBerry;Opera Mini") != -1) OSName="Opera/9.80";

else if(AgentUserOs.indexOf("Symbian/3") != -1) OSName="Symbian OS3";

else if(AgentUserOs.indexOf("SymbianOS/6") != -1) OSName="Symbian OS6";

else if(AgentUserOs.indexOf("SymbianOS/9") != -1) OSName="Symbian OS9";

else if(AgentUserOs.indexOf("Ubuntu") != -1) OSName="Ubuntu";

else if(AgentUserOs.indexOf("PDA") != -1) OSName="PDA";

else if(AgentUserOs.indexOf("NintendoWii") != -1) OSName="Nintendo Wii";

else if(AgentUserOs.indexOf("PSP") != -1) OSName="PlayStation Portable";

else if(AgentUserOs.indexOf("PS2;") != -1) OSName="PlayStation 2";

else if(AgentUserOs.indexOf("PLAYSTATION3") != -1) OSName="PlayStation 3";

else OSName="Linux (Unknown)";

if(AgentUserOs.indexOf("x86_64") != -1) OsVers=", x86_64";

else if(AgentUserOs.indexOf("i686") != -1) OsVers=", i686";

else if(AgentUserOs.indexOf("i686 on x86_64") != -1) OsVers=", i686 running on x86_64";

else if(AgentUserOs.indexOf("armv7l") != -1) OsVers=" Nokia N900 Linux mobile, on the Fennec browser";

else if(AgentUserOs.indexOf("IA-32") != -1) OsVers=" 32-bit";

else OsVers="";

} else if ($.os.Unix) {

OSName="UNIX";

} else if ($.os.Mac) {

if(AgentUserOs.indexOf("iPhoneOS3") != -1) OSName="iPhone OS 3";

else if(AgentUserOs.indexOf("iPhoneOS4") != -1) OSName="iPhone OS 4";

else if(AgentUserOs.indexOf("iPhoneOS5") != -1) OSName="iPhone OS 5";

else if(AgentUserOs.indexOf("iPhoneOS6") != -1) OSName="iPhone OS 6";

else if(AgentUserOs.indexOf("iPhoneOS7") != -1) OSName="iPhone OS 7";

else if(AgentUserOs.indexOf("iPhoneOS8") != -1) OSName="iPhone OS 8";

else if(AgentUserOs.indexOf("iPad") != -1) OSName="iPad";

else if((AgentUserOs.indexOf("MacOSX10_1")||AgentUserOs.indexOf("MacOSX10.1")) != -1) OSName="Mac OS X Puma";

else if((AgentUserOs.indexOf("MacOSX10_2")||AgentUserOs.indexOf("MacOSX10.2")) != -1) OSName="Mac OS X Jaguar";

else if((AgentUserOs.indexOf("MacOSX10_3")||AgentUserOs.indexOf("MacOSX10.3")) != -1) OSName="Mac OS X Panther";

else if((AgentUserOs.indexOf("MacOSX10_4")||AgentUserOs.indexOf("MacOSX10.4")) != -1) OSName="Mac OS X Tiger";

else if((AgentUserOs.indexOf("MacOSX10_5")||AgentUserOs.indexOf("MacOSX10.5")) != -1) OSName="Mac OS X Leopard";

else if((AgentUserOs.indexOf("MacOSX10_6")||AgentUserOs.indexOf("MacOSX10.6")) != -1) OSName="Mac OS X Snow Leopard";

else if((AgentUserOs.indexOf("MacOSX10_7")||AgentUserOs.indexOf("MacOSX10.7")) != -1) OSName="Mac OS X Lion";

else if((AgentUserOs.indexOf("MacOSX10_8")||AgentUserOs.indexOf("MacOSX10.8")) != -1) OSName="Mac OS X Mountain Lion";

else if((AgentUserOs.indexOf("MacOSX10_9")||AgentUserOs.indexOf("MacOSX10.9")) != -1) OSName="Mac OS X Mavericks";

else if((AgentUserOs.indexOf("MacOSX10_10")||AgentUserOs.indexOf("MacOSX10.10")) != -1) OSName="Mac OS X Yosemite";

else OSName="MacOS (Unknown)";

if(AgentUserOs.indexOf("Intel") != -1) OsVers=" on Intel x86 or x86_64";

else if(AgentUserOs.indexOf("PPC") != -1) OsVers=" on PowerPC";

else OsVers="";

} else {

OSName="Unknown OS";

}

  var OSDev = OSName + OsVers;

  return OSDev;

}


// Android의 단말 이름을 반환

function getAndroidDevName() {

var uaAdata = navigator.userAgent;

var regex = /Android (.*);.*;\s*(.*)\sBuild/;

var match = regex.exec(uaAdata);

if(match) {

var ver = match[1];

var dev_name = match[2];

return "Android " + ver + " " + dev_name;

}

return "Android OS";

}


// OSInfoDev() 는 OS이름과 버전 출력하는 함수

// AgentUserOs 는 userAgent 출력

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<!DOCTYPE html>
 
<head>
    <title></title>
</head>
 
<script type="text/javascript">
    function test(name,age){
        this.name = name;
        this.age = age;
    }
    // toString()은 자바스크립트 최상위 Object 객체의 메서드로
    // 모든 객체들은 이 toString을 가지고 있다. 따라서
    // 아래처럼하면 toString()을 재정의한 것이고
    // toString()메서드는 객체명만 기술시 출력할 수 있다.(자바와 same)
    test.prototype.toString = function(){
        return "이름 : " + this.name + " 나이 : " + this.age;
    }
 
    var f = new test("hhh",28);
    alert(f);
 
    // [ 문자열 String 관련 내장 객체 및 메서드 ]
    // 1. 문자열 생성 방법 2가지
    var str = "문자열";
    var str2 = new String("문자열2");
    // 문자열 관련 대표 메서드
        // 문자열 길이
        var strLength = str.length;
        // indexOf("찾을문자열") : 찾을 문자열 시작 인덱스를 반환한다.
        //                      찾는 문자열이 없을시 -1을 리턴한다.
        var startIndex = str.indexOf("자열");
        // replace("old","new");
        str.replace("자열","좌열");
        // match("정규표현식")
        // str.match("정규표현식") : 정규표현식에 일치하는 문자열을 리턴한다.
        // substring(시작인덱스,끝인덱스) : 시작 ~ 끝 까지의 문자열을 반환한다.
        var sub = str2.substring(1,3);
        // toLowerCase() : 소문자로 변환
        var low = str2.toLowerCase();
        // toUpperCase() : 대문자로 변환
        var up = str2.toUpperCase();
 
 
    // [ 숫자관련 내장객체 Number ]
    var num = 10;
    var s = "10";
    var num2 = Number(s); // 숫자로 변환
    // 숫자 관련 대표 메서드 : toFixed(자리수) : 자리수 이하를 버림한다.
    alert(num2.toFixed(1));
    alert(10.23456.toFixed(2));
 
 
    // [ 배열 ]
    var arr1 = [1,2,3,4,5]; // 생성과 동시에 초기화
    var arr2 = new Array(5); // 공간만 생성
    var arr3 = new Array();
 
    // [ 배열관련 메서드 ]
    var arr1Length = arr1.length;
    // push : 배열의 마지막에 데이터를 삽입
    arr1.push("newDataString"); // 자바와 달리 하나의 배열에 여러 타입을 저장할 수 있음.
    // pop : 마지막에 저장한 데이터를 빼옴
    var popData = arr1.pop(); // newDataString
    // splice(시작인덱스,갯수) : 시작인덱스부터 해당 갯수만큼 데이터를 삭제하고, 삭제한 데이터들을 반환함
    var spliceData = arr1.splice(2,3); // 3,4,5 가 spliceData 들어가 있음
    alert("spliceData : " + spliceData);
    alert(arr1); // 1,2
 
 
    // [ Date 객체]
 
        // Date 객체 생성
        var date = new Date();
        // '일' 가져오기
        alert("getData() : " + date.getDate());
        // '월' 가져오기 : 월-1 값이 출력됨을 유의(달만 이렇게...)
        alert("getMonth() : " + date.getMonth()); // 8월이면 7이 출력됨
        // '년' 가져오기
        alert("getFullYear() : " + date.getFullYear());
        // 7일 뒤의 날짜를 구하기 위한 방법
            // 현재 일을 가져와 7을 더하고 세팅
        date.setDate(date.getDate() + 7);
        alert(date);
        date.setFullYear(date.getFullYear() + 2); // 2년뒤
        alert(date);
 
        // 경과시간 구하기
    var date = new Date(); // 현재 날짜 가져오기
    date.setDate(date.getDate() + 7); // 7일 뒤 날짜
    var now = new Date(); // 현재 날짜
    var untilTime = date.getTime();
    var nowTime = now.getTime();
 
    var diffTime = untilTime - nowTime;
    diffTime = diffTime / (1000*60*60*24); // 하루단위로 나눔
    alert("오늘과 일주일뒤의 차이는 7일인가요? : " + diffTime);
 
</script>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
<!DOCTYPE html>
<html>
                                                <head>
                <script type="text/javascript">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":2750468,"name":"rongscodinghistory","title":"악덕고용주의 개발 일기","isDormancy":false,"nickName":"고무곰(GomuGom)","status":"open","profileStatus":"normal"},"NEED_COMMENT_LOGIN":true,"COMMENT_LOGIN_CONFIRM_MESSAGE":"이 블로그는 로그인한 사용자에게만 댓글 작성을 허용했습니다. 지금 로그인하시겠습니까?","LOGIN_URL":"https://www.tistory.com/auth/login/?redirectUrl=https://rongscodinghistory.tistory.com/category/%25EC%258A%25A4%25ED%2584%25B0%25EB%2594%2594/%25EC%259E%2590%25EB%25B0%2594%25EC%258A%25A4%25ED%2581%25AC%25EB%25A6%25BD%25ED%258A%25B8","DEFAULT_URL":"https://rongscodinghistory.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 = null;
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: "",
    token: "NpnG8CE2DKRpN25bUQ1xENl+vwRiQOTBVbT24v1zCUisHpTbf0YjAcxRB77Vdq1Y"
};
var servicePath = "";
var blogURL = "";</script>
 
                 
                 
                 
    <title></title>
 
                <style type="text/css">.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;
}
</style>
 
                 
<link rel="canonical" href="https://rongscodinghistory.tistory.com"/>
 
<!-- BEGIN STRUCTURED_DATA -->
<script type="application/ld+json">
    {"@context":"http://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":0,"item":{"@id":"https://rongscodinghistory.tistory.com/123","name":"자바스크립트로 사용자 OS 버전 확인하는 코드(IE버전 X 운영체제 판별)"}},{"@type":"ListItem","position":1,"item":{"@id":"https://rongscodinghistory.tistory.com/75","name":"자바스크립트 내장객체1(배열,Date,String,Number)"}},{"@type":"ListItem","position":2,"item":{"@id":"https://rongscodinghistory.tistory.com/74","name":"자바스크립트 객체의 캡슐화"}},{"@type":"ListItem","position":3,"item":{"@id":"https://rongscodinghistory.tistory.com/71","name":"eclipse(이클립스) 자바스크립트(javascript) 자동완성 플러그인 설정하기"}},{"@type":"ListItem","position":4,"item":{"@id":"https://rongscodinghistory.tistory.com/67","name":"지역변수,전역변수 개념과 자바스크립트의 객체(Object)"}},{"@type":"ListItem","position":5,"item":{"@id":"https://rongscodinghistory.tistory.com/61","name":"자바스크립트 정리1"}},{"@type":"ListItem","position":6,"item":{"@id":"https://rongscodinghistory.tistory.com/59","name":"자바스크립트 navigator를 이용한 IE 버전 알아내기"}},{"@type":"ListItem","position":7,"item":{"@id":"https://rongscodinghistory.tistory.com/57","name":"자바스크립트로 부모,자식 요소 접근하기"}},{"@type":"ListItem","position":8,"item":{"@id":"https://rongscodinghistory.tistory.com/51","name":"자바스크립트로 제어하고 싶은 대상 선택하기(찾기)"}},{"@type":"ListItem","position":9,"item":{"@id":"https://rongscodinghistory.tistory.com/50","name":"window 객체(location,navigator,screen etc...) : 부모창 자식창간 데이터 주고 받기 포함"}},{"@type":"ListItem","position":10,"item":{"@id":"https://rongscodinghistory.tistory.com/49","name":"location 객체와 navigator 객체"}},{"@type":"ListItem","position":11,"item":{"@id":"https://rongscodinghistory.tistory.com/48","name":"HTML에서 자바스크립트 로드하기"}}]}
</script>
<!-- END STRUCTURED_DATA -->
<link rel="stylesheet" type="text/css" href="//t1.daumcdn.net/tistory_admin/www/style/top/font.css"/>
 
                 
                </head>
<body>
<script type="text/javascript">
    /*
        [    캡슐화    ]
        : 내가 만든 변수에 다른 사용자에 의해 원치않는 값이 대입되는걸 막아야 할
        의도로 사용되어 진다.
        ex) 넓이를 구하는데 필요한 width,height값은 양수만 입력되어야하지만
        사용자가 음수를 입력하면 안되는데 이렇게 음수가 입력되는걸 방지하기 위해
        사용된다.
 
        방법) 외부에서 사용자가 필드변수에 접근하는 것을 막기위해 지역변수로 선언하고
            getter와 setter를 통해서만 접근할 수 있도록 한다.
    */
    function test(){
        /*
            this.nameVal2의 경우 외부에서 접근 가능
            var nameVal은 함수 내부에서 선언시 지역변수로 외부에서 접근이 불가능하다.
            따라서,
        */
        var nameVal = "";
        var ageVal = 0;
        this.nameVal2 = "";
        this.ageVal2 = 0;
         
        this.setterNameVal = function(name){
            nameVal = name;
        }
 
        this.setterAgeVal = function(age){
            if ( age <= 0){
                throw "음수 입력하지마세요";
            }else{
                ageVal = age;  
            }
        }
 
        this.getterNameVal = function(){
            return nameVal;
        }
 
        this.getterAgeVal = function(){
            return ageVal;
        }
    }
 
    test.prototype.info = function(){
        return "소개 : " + this.getterNameVal() + "님의 나이는 : "
             + this.getterAgeVal();
    }
    var f = new test();
    f.setterNameVal("황영롱");
    f.setterAgeVal(28);
 
    alert(f.info());
</script>
 
                <div style="margin:0; padding:0; border:none; background:none; float:none; clear:none; z-index:0"></div>
<script type="text/javascript">window.roosevelt_params_queue = window.roosevelt_params_queue || [{channel_id: 'dk', channel_label: '{tistory}'}]</script>
<script type="text/javascript" src="//t1.daumcdn.net/midas/rt/dk_bt/roosevelt_dk_bt.js" async="async"></script>
 
                 
                <script>window.tiara = {"svcDomain":"user.tistory.com","section":"기타","trackPage":"글뷰_보기","page":"글뷰","key":"2750468","customProps":{"userId":"0","blogId":"2750468","entryId":"null","role":"guest","trackPage":"글뷰_보기","filterTarget":false},"entry":null,"kakaoAppKey":"3e6ddd834b023f24221217e370daed18","appUserId":"null"}</script>
<script src="https://t1.daumcdn.net/tistory_admin/frontend/tiara/v1.0.5/polyfills-legacy.js" nomodule="true" defer="true"></script>
<script src="https://t1.daumcdn.net/tistory_admin/frontend/tiara/v1.0.5/index-legacy.js" nomodule="true" defer="true"></script>
 
                </body>
</html>

[    eclipse(이클립스) 자바스크립트(javascript) 자동완성 플러그인 설정하기    ]



이클립스에서 자바스크립트 사용시 ctrl + space 를 눌러 자동완성이 가능하도록 세팅하는 방법에 대한 포스팅입니다.


두가지 작업을 해주어야 합니다.


1. Help 탭->Eclipse Market place->Webclipse 검색 후 설치(install) 후 restart합니다.



2. 두번째로 window탭->preferences->Ant->editor->Content Assist에서 enable auto activation을 체크합니다.





추가하고 나면 아래와 같이 자동완성이 가능한 것을 볼 수 있습니다.



- 자바스크립트의 지역변수와 전역변수 개념

=> 함수내에 선언된 변수만 지역변수!! 그 외에는 다 전역변수이다. 즉, 함수내에 선언된게 아니면
어떠한 블럭이건 for문 안에서건 전부 전역변수이다.

{
var param = 10;
}
이것도 어면히 전역변수
var f = function(){
var str = "string";
}
이 str변수는 지역변수



[ 자바스크립트의 객체(Object)에 대해서]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
 
<head>
    <title></title>
</head>
 
<script type="text/javascript">
     
    // 자바스크립트는 함수 내부에 선언한 변수만 지역변수이고, 그 외는 전역변수이다.
    // 아무리 {} 이런 블록안이어도 전역변수임!
 
    // 일반적인 객체 생성 방법(선언과 동시에 생성)
    var studentObj = {
        // 필드
        name : "황영롱",
        age : 28,
        // 메서드
        sayHello : function(){
            // 객체 내의 필드변수에 접근할 때는 반드시 this키워드를 써줘야한다.(자바와 다름...생략 불가)
            return this.name + "입니다. 안녕하세요.";
        }
    }
 
    alert(studentObj.name + "입니다. " + studentObj.sayHello());
 
    var students = [];
    // 배열에 객체 추가
    students.push(studentObj);
 
    // 객체명을 생략해 편리하게 이용하도록 도와주는 with
    // 본래 아래와 같이 필드변수에 접근해야한다.
    console.log( studentObj.name + studentObj.age );
    // 하지만... width를 쓰면 다음처럼 접근할 수 있다.
    with(studentObj){
        console.log( name + age );
    }
 
    // 매번 객체에 값을 넣어논 상태로 생성하는 것이 불편하기 때문에 생성자를 이용해 객체를 생성하도록 한다.
    function Student(name,age,kor,math){
         
        this.name = name;
        this.age = age;
        this.kor = kor;
        this.math = math;
 
        this.getSum = function(){
            return (this.kor + this.math);
        }
 
        this.toString = function(){
            return ("이름 : " + this.name + "나이 : " + this.age + "합계 : " + this.getSum() );
        }
 
    }
 
    // 객체 생성
    var s1 = new Student("홍길동",20,100,98);
    // 메서드 호출
    alert(s1.toString());
 
    // 이런 객체 생성방식에서 필드변수의 값은 매번 다를 수 있지만 함수는 매번 똑같기 때문에
    // 매번 메모리를 잡아먹으면 낭비가 된다. 따라서 생성자 함수 정의시 필드 변수만 넣고 메서드는 prototype 객체에 넣도록 한다.
    // prototype 객체는 모든 객체가 공통으로 가지는 객체이다. 이 prototype에 메서드를 등록해서 사용한다.
 
    function Car(name,color){
        this.name = name;
        this.color = color;
        // 필드 변수만 기재한다. 메서드는 따로 prototype에 등록한다.
    }
    // 프로토타입에 메서드 등록
    Car.prototype.performance = function(){
        return this.name + "의 차이며 색상은 : " + this.color + "입니다.";
    }
    Car.prototype.newParam = 10;
 
    var c1 = new Car("아반떼","검정");
    var c2 = new Car("소나타","레드");
    alert(c1.performance());
    alert(c2.performance());
 
    // 이 경우 c1과 c2에 본래 performance메서드가 각각 메모리에 잡히게 되고 만약 이런 객체를 100개를 만들면 100개의 공간이잡힐 것이다.
    // 하지만, 둘 다 공유할 수 있는 prototype이라는 객체에 메모리를 할당해 놓고 두 객체는 이 공간을 공유해 사용하게 되서 메모리를 절약할 수 있게 되는 것이다.
    // 만약, 메서드뿐 아니라 필드변수값도 공유하고 싶다면 아래와같이 할 수 있다.
    // Car.prototype.newParam;
     
    alert("c1의 값 : " + c1.newParam); // 10
    // 이건 공통 prototype에서가 아니라 새로 생성한 것
    c1.newParam = 20;
    // c1, c2 공통으로 공유되는 값을 바꾼 것
    Car.prototype.newParam = 30;
    alert("c1'''의 값 : " + c1.newParam); // 위에서 c1.newParam으로 생성했음으로 자기 newParam을 사용해 20이 나옴
    alert("c2의 값 : " + c2.newParam); // 30
 
</script>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
<!DOCTYPE html>
 
<head>
   <title></title>
</head>
 
<script type="text/javascript">
   // [ typeof(타입을 알고싶은 데이터) ]
   var num1 = 10;
   var str = "문자열";
   var boolVal = true;
   alert("num1 : " + typeof(num1) + " str : " + typeof(str) + " boolVal : " + typeof(boolVal));
   //////////////////////////////
 
   // [ 빈 데이터에 관련된 자료형 ]
      // 'undefined', null, ""
      // 변수 선언 후 초기화하지 않으면 undefined
   var undefi;
   console.log(undefi); // undefined 찍힘
   ////////////////////////////////
 
   // [ confirm("문자열"), prompt(" ")]
   var confirmCheck = confirm("최종 승인하시겠습니까?");
   console.log(confirmCheck); // true or false 반환
   /////////////////////////////////
 
   // [ 문자->숫자, 숫자->문자 변환 ]
   // 1. 문자->숫자
   var str2 = "10"; // 문자 데이터 10
   var sum1 = Number(str2) + 5;
   console.log(sum1); // 15출력
   // 2. 문자->숫자
   var sum2 = parseInt(str2) + 2; // parseInt("문자열") : 정수로 변환
   var sum3 = parseFloat(str2) + 3.4; // parseFloat("문자열") : 실수로 변환
   /////////////////////////////////
 
   // [ indexOf("찾을 문자열") : 리턴 => 찾을 문자열이 있으면 해당 인덱스, 없으면 -1을 반환]
   var str3 = "helloWorld hi";
   if ( str3.indexOf("hi") != -1 ){
      console.log( "hi의 시작 인덱스 : " + str3.indexOf("hi") );
   }
   /////////////////////////////////
 
   // [ 배열관련 length, push ]
   var arr = [1,2,3,4,5];
   console.log("배열의 길이 : " + arr.length;
   arr.push(6); // 배열에 데이터 집어 넣기
   /////////////////////////////////
 
   // [ 선언적 함수 선언 방식과 암시적 함수 선언 방식]
   // 1. 선언적 함수 선언
   function sumAll1(args1,args2){
      console.log("선언적 함수 선언");
   }
   // 2. 암시적 함수 선언
   var func = function(v1,v2){
      console.log("암시적 함수 선언");
   }
   ////////////////////////////////
 
   // [ 가변인자 함수 ]
   // 1. arguments를 이용한 방식
   // 2. ... 을 이용한 방식(IE는 지원하지 않음)
 
   // 1)
   function sum1(){
      var sum = 0;
      for ( var i=0; i<arguments.length; i++ ){
         sum += arguments[i];
      }
      return sum;
   }
   console.log(sum1(1,2,3,4,5));
   console.log(sum1(1,6));
   // 2)
   function sum2(...nums){ // 가독성은 arguments보다 좋다. but IE에서 지원하지 않음
      var sum = 0;
      for(var i=0; i<nums.length; i++){
         sum += nums[i];
      }
      return sum;
   }
   console.log(sum2(1,5));
   console.log(sum2(1,4,5,7,8));
   ///////////////////////////////////////
 
   // [ 매개변수로 함수를 넘기는 콜백함수 ]
      // : 함수도 매개변수로 넘길 수 있다. 주로 이벤트처리 시에 많이 사용된다.
 
   function callbackF(){
      return "callback 메서드";
   }
 
   var callbackTest = function(callback){
      // 함수를 매개변수로 받아 함수를 리턴할 수도 있다. 내부에서도 수행할 수도 있고...
      callback();
      return callback(); // 함수를 리턴
   }
 
   callbackTest(callbackF()); // 매개변수에 함수를 전달해 주었다.
   /////////////////////////////////////////
 
 
   // [ 일정주기마다 수행하는 setInterval()메서드와 일정시간 후에 수행하는 setTimeout() 메서드 ]
      // 각 메서드를 수행하면 각 id를 반환하고 수행을 중단하려면 clearInterval(id), clearTimeout(id)를 하면 된다.
   var intervalId = setInterval(function(){
      console.log("setInterval");
   },1000); // 1초마다 수행
 
   setTimeout(function(){
      clearInterval(intervalId); // id를 지정해 해제
   },10000); // 10초 뒤에 Interval 해제
   ///////////////////////////////////////////
 
   // [ 인코딩, 디코딩 관련 함수 ]
   // 특히 한글 문자열을 주고 받을 때 인코딩, 디코딩이 필요한 경우가 있다.
   // escape()와 같은 인코딩 함수도 잇지만 특수문자는 인코딩되지 않는 등 문제가 있을 수 있음으로
   // 아래 방식을 자주 사용한다.
   var str4 = "안녕하세요.";
   // 인코딩 : encodeURIComponent("인코딩할 문자열");
   var encodeStr = encodeURIComponent(str4);
   // 디코딩 : decodeURIComponent("디코딩할 문자열");
   var decodeStr = decodeURIComponent(encodeStr);
   /////////////////////////////////////////////
 
 
   // [ eval("문자열") 메서드 ] : 문자열을 자바스크립트로 그대로 수행하는 메서드
   console.log( eval("3 + 4") ); // 7 출력
 
 
</script>

[ 브라우저 체크 ]

var agt = navigator.userAgent.toLowerCase();
if (agt.indexOf("chrome") != -1) return 'Chrome'; 
if (agt.indexOf("opera") != -1) return 'Opera'; 
if (agt.indexOf("staroffice") != -1) return 'Star Office'; 
if (agt.indexOf("webtv") != -1) return 'WebTV'; 
if (agt.indexOf("beonex") != -1) return 'Beonex'; 
if (agt.indexOf("chimera") != -1) return 'Chimera'; 
if (agt.indexOf("netpositive") != -1) return 'NetPositive'; 
if (agt.indexOf("phoenix") != -1) return 'Phoenix'; 
if (agt.indexOf("firefox") != -1) return 'Firefox'; 
if (agt.indexOf("safari") != -1) return 'Safari'; 
if (agt.indexOf("skipstone") != -1) return 'SkipStone'; 
if (agt.indexOf("msie") != -1) return 'Internet Explorer'; 
if (agt.indexOf("netscape") != -1) return 'Netscape'; 
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla'; 


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

윈도우8이 발매를 시작하면서 IE10(Internet Explorer)도 이런저런 문제가 생기네요.

우선 자바스크립트로 인터넷익스플로러 버전 체크할때 부터도 문제가 있습니다.

이건 이전 버전의 브라우저도 아직 발생되고 있는 현상인데요.

예를 들어 제가 IE9.0을 사용할 경우 버전을 체크할 경우

navigator.userAgent.indexOf('9.0') 으로 실행할 경우 
30 이란 값이 나옵니다. 유저 정보의 30번째 문자열에 정보가 있다는 것이지요

해당 정보가 없을 경우 -1값을 떨굽니다.

그래서 IE9.0의 버전을 찾을 경우 이런식으로 처리하면 됩니다.

if(navigator.userAgent.indexOf('9.0') == -1) {
  alert('사용중인 IE가 IE9.0 이 아님');
}else{
  alert('사용중인 IE가 9.0임');
}

하지만

Internet Explorer 8.0 부터 있는 기능인 [호환성보기] 기능을 사용할 경우

버전찾기에 문제가 생기게 됩니다. 

정확한 버전을 체크하지 못하게 되죠

alert(navigator.userAgent); 를 실행할 경우 출력값이 다릅니다.

[호환성보기 설정이 되어 있지 않은 경우] - 정상적으로 버전을 구할 수 있습니다.
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" 

[호환성보기 설정이 사용중인 경우] - IE8.0 이상에서는 거의 모두 7.0으로 표기가 됩니다.
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C)"

때문에 위 처럼 버전을 체크할 경우 7.0으로 나오게 됩니다.

이 현상은 IE10에서도 마찬가지 입니다.

그래서 [IE8.0], [IE9.0], [IE10.0]을 사용하는 사람이 [호환성 보기 기능]을 사용한다면 정확한 IE 버전을 체크하기 힘들더군요

확인해 보니.. IE8.0 이상 부터는 유저 정보에 Trident 라는게 붙습니다.

그리고 뒤에는 버전이 출력되지요. 브라우저 별로 보면 아래와 같이 나옵니다.

 IE6.0 = null
 IE7.0 = null
 IE8.0 = Trident/4.0
 IE9.0 = Trident/5.0
IE10.0 = Trident/6.0

아래와 같이 처리를 하면 해당 브라우저의 버전을 체크 할 수 있습니다.

if(navigator.userAgent.match(/Trident\/(\d.\d)/i)[1] == '6.0'){

  alert('IE10 입니다.');

} else{

  alert('IE9 이하 입니다.');



이렇게 처리할 경우 다른 문제점이 하나 더 있습니다.

IE7.0 이하일 경우에는 해당 내용이 없기 때문에 null이 발생됩니다.

그래서 아래와 같이 하면 정상적으로 처리가 됩니다.

var trident = navigator.userAgent.match(/Trident\/(\d.\d)/i);
if(trident != null && trident[1] == "6.0"){
  alert('IE10 입니다.');
} else{
  alert('IE9 이하 입니다.');
}

다른 방법이 있을수도 있겠지만, 분기처리나 기타등등..
 
여튼 이렇게 할 경우 해당 버전을 찾는게 가능합니다.


<!DOCTYPE html>

<html>

  <head>

    <meta charset="utf-8">

    <title></title>

  </head>

  <body>

    <ul>

      <li>HTML</li>

      <li>CSS</li>

      <li id="active">JavaScript</li>

    </ul>

    <script type="text/javascript">

      // 복수개의 li가 선택됨

      var liObjs = document.getElementByTagName('li');

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

        console.log(liObjs[i].innerHTML());

      }

      // 부모 요소로 접근하기

      // jquery에서는 parent()

      var ulObj = liObjs[1].parentNode;

      // 부모요소에서 2번째 자식 요소 제거하기

      ulObj.removeChild(liObjs[1]);

      // 자식 요소 중 첫번째 요소 콘솔 찍기

      console.log(ulObj.childNodes[0]);

    </script>

  </body>

</html>



[ 자바스크립트로 제어하고 싶은 대상 선택하기(찾기) ]





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
document 문서 객체를 이용해 문서 부분에 있는 요소들을 선택해 올 수 있다.
 
    1. document.getElementByTagName
    <ul>
        <li>HTML</li>
        <li class="active" id="activeId">CSS</li>
        <li class="active">JavaScript</li>
    </ul>
    <script type="text/javascript">
        var lis = document.getElementByTagName("li");
        for(var i=0; i<lis.length; i++){
            lis[i].style.color="red";
        }
    </script>
    <script type="text/javascript">
        // 조회 대상을 조금 더 좁혀서 잡아오기
        var lis2 = document.getElementByTagname("li")[0];
    </script>
 
    2. document.getElementByClassName
    <script type="text/javascript">
        var lis3 = document.getElementByClassName("active");
        var lis4 = document.getElementByClassName("active")[1];
    </script>
 
    3. document.getElementById
    <script type="text/javascript">
        lis5 = document.getElementByid("activeid").innerHTML();
    </script>
</textaera>


window 객체


    • Javascript 실행시 가장 상위에 존재하는 객체

      • 변수를 선언하거나 함수 선언시 window 객체안에 선언됨
      • 크롬에서 F12를 눌러 console탭에서 window 객체를 입력해서 다양한 속성들을 조회해볼 수 있음.
    • 표시된 웹 페이지의 정보에 접근하거나 변경을 할 수 있음

      • window.location : 현재 브라우저 창의 주소를 나타내는 객체
      • window.location.href : 브라우저 창에 입력된 주소, 변경 가능
        • ex) window.location.href = "이동하고자하는 url "
        • ex) window.location.replace = "이동하고자하는 url" 위의 것과 차이점은 이동하고나서 뒤로가기 버튼이 활성화되지 않음.
      • window.open : 새창 띄우기
      • window.navigator : 브라우저 자체에 대한 정보
      • window.screen : 디스플레이의 사이즈
      • window.document : 웹 페이지 문서의 HTML, CSS 등에 대한 접근 가능









    • 2. [ window 객체를 이용해 새창을 띄우고 부모창과 자식창 사이에서 값을 주고 받는 방법 ]


    • var windowObj = window.open("새창에서띄울url","창이름","창의설정(옵션값)"); 처럼하면 현재창에서 새로운 창이 뜨게 됩니다. 이때 기존의 창이 부모창이 되고 새로 뜨게된 창이 자식창이되게되는데

      이때, 부모창과 자식창 사이에서 값을 주고 받기 위해서는 띄운 창의 window 객체를 저장할 변수를 선언해 저장해 놔야합니다.(windowObj)

      그런 다음 부모 창에서는 이 windowObj 변수를 이용해 자식창에 값을 전달할 수 있습니다. 예를들어, 

      windowObj.document.text2.value = "값 입력"; 이런식으로 자식창(새창)의 document 객체에 얼마든지 접근할 수 있습니다. 

      그러면, 반대로 자식창에서 부모창으로 값을 보내기 위해서는 어떤 식으로 해야할까요??

      일단, 부모창에서 자식창을 생성하면 이 자식창은 생성과 동시에 opener 라는 객체를 가지게 되고 이 opener는 바로 부모객체의 window 객체를 가리키게 됩니다. 따라서

      opener.document.parentText.value = document.text2.value; 이런식으로 자식에 있는 값을 부모 창으로 넘기는게 가능합니다.


      먼저, windowOpen1.html 즉, 부모창 예제 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
 
  <head>
    <meta charset="utf-8">
    <title>부모창입니다.</title>
  </head>
   
    <input type="text" id="parentText" value="부모창의값" />
    <input type="text" id="receiveFromChild" value=""/>
    <button type="button" onclick="javascript:openChildWindow();">자식창열기</button>
    <script type="text/javascript">
      // 자식창 window 객체를 저장할 변수
      var windowObj;
      function openChildWindow(){
 
        // 새창에 대한 세팅(옵션)
        var settings ='toolbar=0,directories=0,status=no,menubar=0,scrollbars=auto,resizable=no,height=200,width=200,left=0,top=0';
        // 자식창을 열고 자식창의 window 객체를 windowObj 변수에 저장
        windowObj = window.open("windowOpen2.html","자식창",settings);
 
        // 자식창의 childText라는 id를 가진 태그 요소의 값에 부모창의 값을 넣음
        windowObj.document.getElementById("childText").value = document.getElementById('parentText').value;
      }
    </script>
  



다음으로 windowOpen2.html 즉, 자식창 예제 코드입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
 
  <head>
    <meta charset="utf-8">
    <title>자식창</title>
  </head>
   
    부모창에서 전달받은 값 : <input type="text" id="childText" />
    <button type="button" name="button" onclick="sendToParent();">부모에게 전달</button>
    <script type="text/javascript">
      function sendToParent(){
        var txt = document.getElementById("childText").value + "자식창 값을 +합니다.";
        // opener 를 이용해 부모 window 객체에 접근할 수 있습니다.
        // 부모에게서 전달받은 값에 추가로 문자열을 더해서 다시 부모의 receiveFromChild 라는 id를 갖는
        // 태그요소에 value 값을 바꾸어 주는 작업입니다.
        opener.document.getElementById("receiveFromChild").value = txt;
 
        // 창을 닫음
        window.close();
      }
    </script>
  


위의 예제는 동일 폴더 내에서 테스트한걸로 크롬 보안상 작동하지 않을 수 있지만, 웹 서버에서 할 때는 잘 작동한다는 점 참고해주시기 바랍니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Location 객체 :
 
        window객체의 프로퍼티로 문서의 주소와 관련된 객체이다.
 
        => 이 객체를 통해 윈도우의 문서 URL을 변경할 수 있고, 문서를 해당 URL로 이동하도록 제어할 수 있다.
 
        <script type="text/javascript">
            console.log("현재 주소 : " + window.location.href);
            console.log(location.toString(),location.href);
 
            // URL Parsing
            //      : location 객체는 URL을 의미에 따라서 별도의 프로퍼티로 제공하고 있다.
            console.log(location.protocol, location.host, location.port, location.pathname, location.search, location.hash);
 
            // 현재 문서를 http://www.google.com으로 이동한다.
            //location.href="http://www.google.com";
 
            // 또 다른 방식
            //self.location="http://www.naver.com";
 
            // 현재 문서를 리로드한다.
            //location.reload();
        </script>
 
 
    navigator 객체 :
 
        window 객체의 프로퍼티로 "브라우저의 정보를 제공하는 객체이다."
                => 주로 "호환성 문제"등을 위해 사용한다.
        <script type="text/javascript">
            // 다음과 같이하면 해당 브라우저 정보를 얻을 수 있다.
            console.log(navigator);
            // [ 브라우저 정보 ]
            // 1. appName : 웹브라우저 이름(크롬은 Nescape)
            // 2. appVersion : 버전정보
            // 3. userAgent : 브라우저가 서버측으로 전송하는 USER_AGENT HTTP 헤더의 내용이다.
        </script>

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

1. Javascript Inline 방식 : 

<input onclick="alert('hello world')" type="button" name="inline"><br/>


2. <h2 id="hw">script 태그 내에 삽입하는 방식 :</h2>


<script type="text/javascript">

var hw = document.getElementById("hw");

hw.addEventListener("click",function(){

alert("hello world");

})

</script>

<br/>


3. 외부 파일로 분리하는 방식 :

<script type="text/javascript" src="./script2.js"></script>

<br/>


4. 스크립트의 위치 :


스크립트는 어느 위치에나 올 수 있지만 body 태그의 마지막 부분에 위치시키는 것이 좋다.

why??

=> 제어할려는 태그가 다 로딩된 다음에 작업이 수행되어야 하니까(로딩되지 않은 상태에서 작업시 제어 불가)


=> 위치에 상관없이 태그가 다 로딩된 후 수행토록 하려면

: javascript의 경우

=> window.onload = function(){

이 내부 코드는 태그가 다 로딩된 이후 수행하게 된다.

      }


     jquery의 경우

      => document.ready(function(){


      })



</body>

</html>


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

script.js 파일

window.onload = function(){
// 웹브라우저의 모든 구성요소가 로딩된 이후에 수행되게 됨. window.onload = function(){}
var hw = document.getElementByid("hw");
hw.addEventListener("click",function(){
alert("외부 스크립트 파일");
});
}


+ Recent posts