테스트 사이트 - 개발 중인 베타 버전입니다

자바스크립트 기초문서

· 19년 전 · 2844
들어가면서 -----------------------
http://www.javapassion.com/j2ee/JavaScript.pdf 의 파일내용을 번역한것이다.

이것은 ajax의 제 3강에 해당된다. 하지만.. 전체가 자바스크립트에 대한 설명이다.

이문서의 바로 앞쪽이야기는
http://sir.co.kr/bbs/tb.php/pl_ajax/50 를 참고하고 이쪽 게시판에 전반적인 앞부분이 있다.

하지만.. 이문서는 단지 자바스크립트에 대한설명만 존재한다.

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

JavaScript Basics & JavaScript Basics & HTML DOM

Sang Shin Sang Shin
Java Technology Architect Java Technology Architect
Sun Microsystems, Inc. Sun Microsystems, Inc.
sang.shin@sun.com sang.shin@sun.com
www.javapassion.com


포기 & 승인
상신은 선마이크로시스템의 정직원임에도 불구하고 여기의 이내용들은 그 자신의 노력만으로 회사의 어떤한 부분적 지원도 받은 않은 상태에서 작성된것이다.

승인
이 내용은 자바스크립트 안내서 www.w3cschools.com 으로부터 제작되었다.


3 -------------------------------------
주제
1. 자바스크립트란 무엇인가
2. 어디에 그리고 어떻게 자바스크립트 코드를 넣는가?
3. 자바스크립트 랭귀지
4. 자바스크립트 함수
5. 자바스크립트 이벤트
6. 자바스크립트 개체
7. 자바스크립트 HTML DOM 개체

4----------------------------------------

왜 무엇때문에 자바스크립인가?

5--------------------------------------
1. HTML페이지에 좀더 상호적인 효과를 추가하기위하여 디자인되었다.
2. 스크립적인 언어이다.(scripting language는 가볍게 프로그램 가능한 언어이다.)
3. 자바 스크립트 코드는 일반적으로 html페이지에 바로 포함되어진다.
4. 자바스크립는 interpreted 언어이다.(이말은 컴파일 없이 실행할수 있다.)


6--------------------------------------
자바스크립트로 무엇을 할수 있나?
1. 자바스크립는 html designers 들에게 프로그래밍 기능을 준다.
2. 자바스크립트는 html 페이지에 다이나믹한 문자효과를 넣을수 있다.
3. 자바스크립트 이벤트에 반응할수 잇따.
4. 자바스크립트는 html개체를 읽고 쓸수 있다.
5. 자바스크립트는 변수적 데이타를 사용되어지는것이 가능하다
6. 자바스크립트는 방문자의 브라우저를 알아내는데 사용되어지는것이 가능하다
7. 자바스크립트는 쿠키제작 사용이 가능하다


7----------------------------------------

어떻게 그리고 어디에 자바스크립트를 넣을것인가?


8----------------------------------------
htim페이지에 어떻게 자바스크립트 코드를 입력할것인가?

1. <script> tag를 사용한다.(물론 type의 속성을 스크립트 랭퀴지로 정의한다.)

<html>
<head>
<script type="text/javascript"> <--------------
...
</script> <--------------
</head>

<body>
<script type="text/javascript">
...
</script>
</body>
</html>

9-------------------------------------------
스크립트는 <head> 부분이거나 <body> 부분에 위치할수 있다.
<head>부위에 넣는것이 일반적이다.

<html>
<head>
<script type="text/javascript">
....
</script>
</head>

10----------------------------------------

외부 자바스크립트 파일을 참조하는것

1. 스크립트들은 지역이거나 또는 원격적인 접속이 가능한 자바스크립트 파일을 제공할수 있다.

<html>
<head>
<script language="JavaScript"
type="text/javascript"
src="http://somesite/myOwnJavaScript.js">
</script>
<script language="JavaScript"
type="text/javascript"
src="myOwnSubdirectory/myOwn2ndJavaScript.js">
</script>

11--------------------------------------

자바 스크립트 언어

12----------------------------------------

자바 스크립트 변수

1. var명령을 쓰거나 또는 쓰지 않더라도 변수를 생성한다.
var strname = some value
strname = some value

2. 함수내에서 변수를 선언할때, 변수는 그 함수내에서만 접근이 가능하다
3. 만약 당신이 함수의 외부에서 변수를 선언하면, 당신의 페이지내의 모든 함수에서 접근이 가능하다
4. 그 변수의 사용가능한 lifetime은 변수의 선언됨으로 사용할수 있고 그리고 그 페이지가 닫혀질때까지이다.

13---------------------------------------
자바 스크립트 Popup Boxes

&#8226; Alert box 경고 박스
> User will have to click "OK" to proceed
> alert("sometext")

&#8226; Confirm box 확인형 박스
> User will have to click either "OK" or "Cancel" to proceed
> confirm("sometext")

&#8226; Prompt box 입력 박스
> User will have to click either "OK" or "Cancel" to proceed after
entering an input value
> prompt("sometext","defaultvalue")

**역자주 : prompt box에 대해서 부서적으로 설명을 하면
일반적으로
> prompt("sometext","defaultvalue")에서 sometext형태의 메세지가 나오고
기본입력값으로 "defaultvalue"가 나온다.. 즉 여기에 아무것도 입력하지 않으면
아무값도 없이 입력을 원하게 된다. 그리고 그 옆에.. 입력 또는 취소정도의 버튼이 있을것이다.
가볍게 테스트 하기 위해서는 test.html에다가 아래의 내용을 넣고 익스플로워에서 보도록 하여라

<html>
<head>
<script type="text/javascript">
prompt("sometext","defaultvalue");
</script>
</head>
<body>
</body>
</html>



14------------------------------------------

자바스크립트 언어

&#8226; Conditional statement 조건문
> if, if.. else, switch

&#8226; Loop 반복문
> for loop, while loop

&#8226; try...catch

&#8226; throw

15----------------------------------------

자바 스크립트 함수

16----------------------------------------

자바 스크립트 함수

1. 자바스크립트 함수는 코드를 포함하는데 그것은 이벤트나 또는 그 함수로 호출되어 실행되어지는 것이다.
-페이지를 읽어들인후 곧 브라우저는 실행 스크립트를 유지한다, 스크립트를 함수형태로 적을수 있다.

2. 페이지의 어느곳에 있는 함수이던지 호출이 가능하다(만약 그 함수가 외부포함형 .js 파일로 포함되어져 있다면 다른페이지로 부터도 가능하다)

3. 함수는 <head> or <body> 부분에 정의한다.
- 관례적으로 표준적인 정의는 <head> 부분을 사용한다.

17-----------------------------------------
자바 함수의 예제
<html>
<head>
<script type="text/javascript">
// If alert("Hello world!!") below had not been written within a
// function, it would have been executed as soon as the page was loaded.
function displaymessage() {
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

18--------------------------------------

자바스크립트 이벤트

19----------------------------------------
Events & Event Handlers

1. 웹페이지내의 모든개체는 이벤트를 포함하고 있다. 이벤트는 이벤트 핸들러의 실행을 발생시키는것이다.
2. html테크에 정의된 이벤트와 이벤트 핸들러로 속성이 넣어진다.

3. 이벤트의 예제들
> A mouse click
> A web page or an image loading
> Mousing over a hot spot on the web page
> Selecting an input box in an HTML form
> Submitting an HTML form
> A keystroke

20~22------------------------------------------
이벤트들

&#8226; onabort - Loading of an image is interrupted 이미지가 불러지지 않을때
&#8226; onblur - An element loses focus 개체가 focus를 잃을때
&#8226; onchange - The content of a field changes 필드의 내용이 바뀔때
&#8226; onclick - Mouse clicks an object 개를 마우가 클릭했을때
&#8226; ondblclick - Mouse double-clicks an object 개체를 마우스가 더블클릭했을때
&#8226; onerror - An error occurs when loading a document or an image 문서나 이미지를 로딩시에 에러가 발생할때
&#8226; onfocus - An element gets focus 개체가 focus를 가질때
&#8226; onkeydown - A keyboard key is pressed 키보드가 눌러졌을때
&#8226; onkeypress - A keyboard key is pressed or held down 키보드를 누르거나 또는 계속 누르고 있을때
&#8226; onkeyup - A keyboard key is released 키보드가 풀려짐(눌러진것이 놓음)
&#8226; onload - A page or an image is finished loading 페이지나 이미지가 불러짐이 마침
&#8226; onmousedown - A mouse button is pressed 마우스 버튼 눌러짐
&#8226; onmousemove - The mouse is moved 마우스가 움직임
&#8226; onmouseout - The mouse is moved off an element 개체내에서 마우스가 나감
&#8226; onmouseover - The mouse is moved over an element 개체위에 마우스가 올려짐
&#8226; onmouseup - A mouse button is released 마우스 버튼이 풀려짐(눌러진걸 놓음)
&#8226; onreset - The reset button is clicked 리셋버튼이 클릭됨
&#8226; onresize - A window or frame is resized 창이나 프레임이 사이즈 변경됨
&#8226; onselect - Text is selected 문자가 선택됨
&#8226; onsubmit - The submit button is clicked 제출버튼이 클릭되어짐
&#8226; onunload - The user exits the page 유저가 페이지를 빠저나감

23--------------------------------------------
onload & onUnload Events

1. 페이지가 불러지거나 또는 페이지에서 유저가 나갈때 onload와 onunload이벤트가 발생되어진다.
2. onload 이벤트는 방문자의 브라우저 타입과 브라우저의 버전 그리고 정보에 따른 적정한 페이지를 불러오는데 사용되어진다.
3. onload 와 onunload이벤튼 또한 종종 쿠키를 처리하거나 이것에 유저가 들어오거나 또는 페이지를 벗어나는것을 기록할수 있다.

24---------------------------------------------
onFocus, onBlur and onChange
onFocus, onBlur 그리고 onChange 이벤트들은 종종 폼필드의 확인을 위하여 사용된다.

예를 들어
checkEmail()함수는 사용자가 필드의 내용을 바꿀때마다 호출이 되어진다.
<input type="text" size="30"
id="email" onchange="checkEmail()">

25----------------------------------------------
Example & Demo: onblur

<html>
<head>
<script type="text/javascript">
function upperCase() {
var x=document.getElementById("fname").value
document.getElementById("fname").value=x.toUpperCase()
}
</script>
</head>
<body>
Enter your name:
<input type="text" id="fname" onblur="upperCase()">
</body>
</html>

26-------------------------------------------------
onSubmit

1. onSubmit 이벤튼 모든폼의 내용이 제출전에 확인을 위하여 사용되어진다.
2. 예 : checkform() 함수는 불러질것이다. 사용자가 폼안의 submit버튼을 클릭할때 만약 필드의 값이 허용되지 않는다면 제출은 취소가 될것이다. checkform() 이 함수는 true나 false를 돌려줄것이다. 만약 이것이 true를 돌려주면 제출이되어지고 그렇치않으면 제출은 취소되어질것이다.

<form method="post" action="xxx.html" onsubmit="return checkForm()">


27---------------------------------------------------
Example & Demo: onSubmit
<html>
<head>
<script type="text/javascript">
function validate() {
// return true or false based on validation logic
}
</script>
</head>
<body>
<form action="tryjs_submitpage.htm" onsubmit="return validate()">
Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />
Age (from 1 to 100): <input type="text" id="age" size="20"><br />
E-mail: <input type="text" id="email" size="20"><br />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>

28-------------------------------------------------------

onMouseOver and onMouseOut

1. onmouseover와 onmouseout은 종종 animated 버튼을 만드는데 사용되어진다.
2. 아래의 예제는 onmouseover 이벤트이다. onmouseover이벤트가 생길때 경고박스가 나타날것이다.
<a href="http://www.w3schools.com"
onmouseover="alert('An onMouseOver event');return false">
<img src="w3schools.gif" width="100" height="30">
</a>


29-------------------------------------------------------

JavaScript Objects


30------------------------------------------------------------
JavaScript Objects

1. 자바스크립트 는 OOP형태의 개체 지향형 프로그래밍 언어이다.
2. 자바스크립트의 개체는 속성과 methode를 가진다.
Example: String JavaScript object has length property and
toUpperCase() method
<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
document.write(txt.toUpperCase())
</script>

31-------------------------------------------------------
JavaScript Built-in Objects
&#8226; String
&#8226; Date
&#8226; Array
&#8226; Boolean
&#8226; Math

32------------------------------------------------
자바스크립트 개체 Vs. 자바 개체

유사점
둘다 속성과 매서드를 가진다.

다른점
자바스크립트개체는 동적 형태가 가능하지만 자바 개체는 정적 형태이다.


33 -------------------------------------------------
자바 개체의 생성

두가지 방법
> Create a direct instance of an object
> Create a template of an object


34 -----------------------------------------------
개체의 직접적인 생성법

1. 직접적 개체생성과 4개의 속성을 추가하기
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"

2. 매서드 추가 - 매서드는 eat()함수를 호출하여 personObj추가한다. - 자바의 매서드 정의되는것과는 다르다.

personObj.eat=eat


35~36 ----------------------------

자바스크립트 개체 탬플릿의 생성

1. 이 템플릿은 자바스크립트의 구조를 정의한다.
function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

2. 주의 : 이 템플릿은 단지 함수이다.

3. 일단 템플릿을 가지게 되면, 새로운 개체의 instance생성이 가능하다
myFather=new person("John","Doe",50,"blue");
myMother=new person("Sally","Rally",48,"green");

4. 또한 개인적 개체에 어떤 매서드를 추가하는것도 가능하다, 이것 또한 템플릿 안에서 끝난다.

function person(firstname,lastname,age,eyecolor) {
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.newlastname=newlastname; <-----------------------
}


37-----------------------------
개체에 단지 함수를 붙이는것이 매서드이다.

function newlastname(new_lastname) {
this.lastname=new_lastname
}


38---------------------------------------------

HTML DOM Objects


39---------------------------------------------

HTML DOM Objects

1. html dom 은 html에 대한 개체를 표준을 정의하는것이다.
그리고 접근의 표준적 방법과 html문서를 다룬다.

2. 모든 html개체는 그것의 포함되어진 글자와 속성에 따라, DOM을 통하여 접근되어지는것이 가능하다.
- 내용은 수정되어지거나, 또는 지워거나 그리고 새로운 개체가 생성되어진다.

3. Html Dom은 플랫폼과 언어에 독립적이다.
- 이것은 어떤언어로도 프로그램이 가능하며, 자바, 자바스크립트, 그리고 vbscript로도 가능하다

40~41-----------------------------------

HTML DOM Objects
&#8226; Anchor object
&#8226; Document object
&#8226; Event object
&#8226; Form and Form Input object
&#8226; Frame, Frameset, and IFrame objects
&#8226; Image object
&#8226; Location object
&#8226; Navigator object
&#8226; Option and Select objects
&#8226; Screen object
&#8226; Table, TableHeader, TableRow, TableData objects
&#8226; Window object


42 -------------------------------------

Document Object


43 -------------------------------------

Document Object : Write text to the output

<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>


44----------------------------------------
Document Object: Write text with Formatting to the output
<html>
<body>
<script type="text/javascript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>


45 -----------------------------------------
Document Object: Use getElementById()

<html>
<head>
<script type="text/javascript">
function getElement() {
var x=document.getElementById("myHeader")
alert("I am a " + x.tagName + " element")
}
</script>
</head>
<body>
<h1 id="myHeader" onclick="getElement()">Click to see what element I am!</h1>
</body>
</html>


46------------------------------------------

Document Object: Use getElementsByName()

<html>
<head>
<script type="text/javascript">
function getElements() {
var x=document.getElementsByName("myInput")
alert(x.length + " elements!")
}
</script>
</head>
<body>
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<input name="myInput" type="text" size="20"><br />
<br />
<input type="button" onclick="getElements()" value="How many elements named
'myInput'?">
</body>
</html>

47------------------------------------------
Document Object: Return the innerHTML of the first anchor in a document

<html>
<body>
<a name="first">First anchor</a><br />
<a name="second">Second anchor</a><br />
<a name="third">Third anchor</a><br />
<br />
InnerHTML of the first anchor in this document:
<script type="text/javascript">
document.write(document.anchors[0].innerHTML)
</script>
</body>
</html>


48-------------------------------------------
Document Object: Access an item in a collection

<html>
<body>
<form id="Form1" name="Form1">
Your name: <input type="text">
</form>
<form id="Form2" name="Form2">
Your car: <input type="text">
</form>
<p>
To access an item in a collection you can either use the number or the name of the item:
</p>
<script type="text/javascript">
document.write("<p>The first form's name is: " + document.forms[0].name + "</p>")
document.write("<p>The first form's name is: " + document.getElementById("Form1").name
+ "</p>")
</script>
</body>
</html>


49-----------------------------------------------
Event Object



50~ 끝까지 모두 예제임.. -----------------------
Event Object: What are the coordinates of the cursor?

<html>
<head>
<script type="text/javascript">
function show_coords(event) {
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)
}
</script>
</head>
<body onmousedown="show_coords(event)">
<p>Click in the document. An alert box will alert the x and y coordinates of the
cursor.</p>
</body>
</html>

---------------------
Event Object: What is the unicode of the key pressed?


<html>
<head>
<script type="text/javascript">
function whichButton(event) {
alert(event.keyCode)
}
</script>
</head>
<body onkeyup="whichButton(event)">
<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key
pressed.</p>
</body>
</html>


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

Event Object: Which element was clicked?

<html>
<head>
<script type="text/javascript">
function whichElement(e) {
var targ
if (!e) var e = window.event
if (e.target) targ = e.target
else if (e.srcElement) targ = e.srcElement
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode
var tname
tname=targ.tagName
alert("You clicked on a " + tname + " element.")
}
</script>
</head>
<body onmousedown="whichElement(event)">
<p>Click somewhere in the document. An alert box will alert the tag name of the element you clicked on.</p>
<h3>This is a header</h3>
<p>This is a paragraph</p>
<img border="0" src="ball16.gif" width="29" height="28" alt="Ball">
</body>
</html>


-----------------------
Event Object: Which event type occurred?

<html>
<head>
<script type="text/javascript">
function whichType(event) {
alert(event.type)
}
</script>
</head>
<body onmousedown="whichType(event)">
<p>
Click on the document. An alert box will alert which type of event occurred.
</p>
</body>
</html>


54 ------------------------------

JavaScript Basics JavaScript Basics
Sang Shin Sang Shin
Java Technology Architect Java Technology Architect
Sun Microsystems, Inc. Sun Microsystems, Inc.
sang.shin@sun.com sang.shin@sun.com
www.javapassion.com www.javapassion.com<div class='small'>[이 게시물은 관리자님에 의해 2011-10-31 16:57:14 JavaScript에서 이동 됨]</div>

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
28772
10555
10554
10553
28770
28769
10552
10551
28768
10550
10549
10548
10547
28767
10546
10545
10544
28766
10541
10540
10538
10537
10535
10534
10533
10532
28760
10531
10530
28759
10527
10525
10523
10520
28758
28757
10519
10518
10517
10515
28756
10514
10512
10511
10510
10509
10508
10507
28755
28751
10506
10505
10504
10503
10499
10487
28748
10486
28747
10484
10483
10482
28746
10480
10476
10473
10472
28745
10460
10456
28739
10455
28738
10451
10448
10446
10445
10444
10442
10439
10408
10403
10400
10398
10397
10396
10391
10390
28733
10389
10383
10378
28732
10342
28731
10335
28730
28729
28727
10332