JavaScript Basics

Toggle Space Navigation Tree
Space Map

스크립트가 뭔지 살펴 보자구요.

JavaScript Basics

Table of Contents

자바스크립트는 무엇이며 왜 사용하는가?

  1. 자바스크립트란 무엇인가?
    • HTML 페이지들과 대화하기 위해 디자인되었다.
    • 스크립팅 언어이다. 스크립팅 언어란 경량(가벼운)의 프로그래밍 언어이다.
    • 자바스크립트 코드는 일반적으로 HTML 페이지들 안에 직접 임베드된다.
    • 자바스크립트는 인터럽트 언어이다. 이것은 스크립트가 사전에 편집(사전오류검출?)되지 않고 실행되는것을 의미한다.
  2. 자바스크립트로 무엇을 할수 있는가?
    • 자바스크립트는 HTML디자이너들에게 프로그래밍 툴을 제공한다.
    • 자바스크립트는 HTML페이지안에 동적인 text를 넣을 수 있다.
    • 자바스크립트는 이벤트에 반응 할 수 있다.
    • 자바스크립트는 HTML elements들을 읽고 쓸수 있다.
    • 자바스크립트는 데이타 검증에 사용될 수 있다.
    • 자바스크립트는 사용자들의 브라우저를 인지하는데 사용될 수 있다.
    • 자바스크립트는 쿠키들을 생성하는데 사용될 수 있다.

자바스크립트 코드를 어떻게 언제 위치시키는가?

  1. HTML 페이지안에 자바스크립트를 넣는 방법
    • <script> tag를 사용한다. type 속성은 스크립팅 언어로 선언한다.
    • <head>,<body> 태그 안에 넣을 수 있다.
    • <head> 부분에 위치시키는것이 관례이다.
      <html>
      <head>
      <script type="text/javascript">
      ....
      </script>
      </head>
      <body>
      <script type="text/javascript">
      ....
      </script>
      </body>
      
  2. 외부 자바스크립트 파일 참조하기
<html>
<head>
<script language="JavaScript" type="text/javascript" src="http://somesite/myWonJavaScript.js"></script>
<script language="JavaScript" type="text/javascript" src="http://myOwnSubdirectory/myOwn2ndJavaScript.js"></script>
....
</head>
....
</html>

자바스트립트 언어

  1. 변수
    • var 구문을 사용하거나, 사용하지 않고 변수를 생성할 수 있다.
      var strname = some value;
      strname = some value;
      
    • 함수 내부에서 변수가 선언되었을때, 그 변수는 함수안에서만 접근할 수 있다.
    • 함수 외부에서 변수가 선언되었을때, 페이지안의 모든 함수는 그 변수에 접근할 수 있다.
    • 변수의 수명은 변수가 선언되었을때 시작되고, 페이지가 클로즈될때 끝난다.
  2. 팝업박스
    • Alert Box : OK를 클릭하여 진행한다.
      alert("sometext"); 
      
    • Confirm Box : OK, Cancle을 클릭하여 진행한다.
      confirm("sometext");
      
    • Prompt Box : input 값을 입력한 후에 OK, Cancle을 클릭하여 진행한다.
      prompt("sometext","defaultvalue");
      
  3. 언어
    • 조건문
      > if, if..else, switch
    • 반복
      > for loop, while loop
    • try...catch
    • throw

자바스트립트 함수

  1. 자바스크립트 함수
    • 자바스크립트 함수는 이벤트 또는 그 함수를 호출하여 실행할 수 있는 약간의 코드를 포함한다.
    • 페이지안의 어디서든지 함수를 호출할 수 있다. (외부 .js 파일안에 임베드된 다른페이지라도)
    • 함수는 <head>,<body> 구간에 선언된다. 일반적으로 <head>구간에 선언한다.
    • Example : 자바스크립트 함수
      <html>
      <head>
      <script type="text/javascript">
          function displayMessage(){
              alert("Hello World!");
          }
      </script>
      </head>
      <body>
      <form>
      <input type="button" value="Click Me!" onclick="displayMessage()">
      </form>
      </body>
      </html>
      

자바스트립트 이벤트

  1. 이벤트 & 이벤트 핸들러
    • 웹페이지위의 모든 element는 이벤트 핸들러의 호출을 일으킬 수 있는 약간의 이벤트를 가진다.
    • 속성들은 이벤트와 이벤트 핸들러를 선언하기위해 HTML 태그안에 삽입된다.
    • Examples of events
      > 마우스 클릭
      > 웹페이지 또는 이미지 로딩
      > 웹페이지의 hot spot(클릭할 수 있는 위치)위에서의 마우스 움직임
      > HTML form 안의 input box 선택
      > HTML form의 submit
      > 키를 치는것
  2. 이벤트들
    • 이벤트 종류
      • onabort - 이미지 로딩중 중단될때
      • onblur- element가 포커스를 잃었을때
      • onchange - 필드의 내용이 변경되었을때
      • onclick - 객체를 마우스 클릭했을때
      • ondbclick - 객체를 마우스 더블클릭했을때
      • onerror - 문서나 이미지가 로딩될때 에러가 발생했을때
      • onfoucs - element가 포커스를 얻었을때
      • onkeydown - 키보드의 키를 눌렀을때
      • onkeypress - 키보드의 키를 누르거나 놓았을때
      • onkeyup - 키도브 키를 놓았을때
      • onload - 페이지 또는 이미지의 로딩이 끝났을때
      • onmousedown - 마우스 버튼을 눌렀을때
      • onmousemove - 마우스를 움직일때
      • onmouseout - 마우스가 element를 벗어났을때
      • onmouseover - 마우스를 element위로 이동할때
      • onmouseup - 마우스버튼을 놓았을때
      • onreset - 리셋버튼을 클릭했을때
      • onresize - 윈도우 또는 프레임이 크기가 변했을때
      • onselect - text가 선택되었을때
      • onsubmit - submit 버튼을 클릭했을때
      • onunload - 사용자가 페이지를 나갈때
  3. onload & onUnload Events
    • onload와 onUnload 이벤트는 사용자가 페이지에 들어오거나 나갈때 발생한다.
    • onload 이벤트는 종종 방문자의 브라우저 타입과 버전, 정보에 기반한 웹페이지의 고유한 버전을 체크하는데 사용된다.
    • onload와 onUnload 두 이벤트는 사용자가 페이지에 들어오거나 나갈때 기록된 쿠키들을 처리하기 위해 사용된다.
  4. onFocus, onBlur and onChange
    • onFocus, onBlur, onChange 이벤트는 폼 필드들이 유효성과 함께 결합되어 사용된다.
    • Example: checkEmail() 함수는 사용자가 필드의 내용을 변경할때마다 호출된다.
      <input type="text" size="30" id="email" onchange="checkEmail()">
    • 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>
      
  5. onSubmit
    • onSubmit 이벤트는 모든 폼 필드들이 submit 되기전에 유효성을 체크하는데 사용된다.
    • Example: checkForm() 함수는 사용자가 폼안의 submit 버튼을 클릭했을때 호출된다.
      만약 필드의 값에 접근되지 않으면, submit은 취소된다. checkForm()함수는 true또는 false를 리턴한다.
      만약 폼에서 true가 리턴되면 submit이 될것이고, false가 리턴되면 submit은 취소될것이다.
      <form method="post" action="xxx.html" onsubmit="return checkForm()">
    • onSubmit 예제
      <html>
      <head>
      <script type="text/javascript">
          function validate(){
              //return true or false based on validation logic;
          }
      </script>
      </head>
      <body> 
      <form action="tryjs_submitpage.html" onsubmit="return validate()">
          Name(max 10 characters) : <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>
      
  6. onMouseOver and onMouseOut
    • onMouseOver, onMouseOut 이벤트는 animated 버튼을 생성할때 사용된다.
    • Example : onMouseOver 이벤트가 발견되었을때, alert box가 나타난다.
      <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false;">
      <img src="w3schools.gif" width="100" height="30">
      </a>

자바스트립트 객체

  1. 자바스크립트 객체
    • 자바스크립트는 Object Oriennted Programming(OOP) 언어이다.
    • 자바스크립트 객체는 속성들과 메소드를 가진다.
      > Example : String 자바스크립트 객체는 length 속성과 toUpperCase()메소드를 가진다.
      <script type="text/javascript">
          var txt = "Hello World!";
          document.write(txt.length);
          document.write(txt.toUpperCase());
      </script>
      
  2. 자바스크립트 내장 객체
    • String
    • Date
    • Array
    • Boolean
    • Math
  3. 자바스크립트 객체 vs 자바 객체
    • 유사점
      > 앙쪽모두 속성과 메소드를 가진다.
    • 차이점
      > 자바스크립트 객체는 동적인 타입인데 반해 자바객체는 정적인 타입이다.
  4. 사용자 고유의 자바스크립트 객체 생성하기
    • 두가지 다른 방법
      > 객체의 인스턴스를 직접 생성한다.
      > 객체의 템플릿을 생성한다.
  5. Option1 : 자바스크립트 객체의 인스턴스를 직접 생성한다.
    • 객체의 인스턴스를 생성하고, 네가지 속성을 추가한다.
    • 메소드를 추가한다. - personObj에 eat() 호출하는 메소드를 추가한다. 자바 메소드를 선언하는 방법과 차이가 있다.
      personObj = new Object();
      personObj.firstname = "John";
      personObj.lastname = "Doe";
      personObj.age = "50";
      personObj.eyecolor= "blue";
      
      personObj.eat = eat;
      
  6. Option2 : 자바스크립트 객체의 템플릿을 생성한다.
    • 템플릿은 자바스크립트 객체의 구조에 대한 정의이다.
      function persion(firstname, lastname, age, eyecolor){        
          this.firstname = firstname;
          this.lastname = lastname;
          this.age = age;
          this.eyecolor= eyecolor;
      }
      
    • 템플릿은 단지 함수에 기록한다.
    • 사용자는 하나의 템플릿을 가지고 있으면, 객체의 새로운 인스턴스를 생성할 수 있다.
      myFather = new person("John","Doe","50","blue");
      myMother = new person("Sally","Rally","48","green");
      
    • 사용자는 persion 객체에 약간의 메소드를 추가할 수 있다. 메소드는 템플릿 안에 존재한다.
      function persion(firstname, lastname, age, eyecolor){        
          this.firstname = firstname;
          this.lastname = lastname;
          this.age = age;
          this.eyecolor= eyecolor;
          this.newlastname= newlastname;
      }
      
  7. 메소드는 자바스크립트 함수이다.
    • 메소드들은 자바객체에 첨부된 단지 함수들이다.

자바스트립트 HTML DOM 객체

  1. HTML DOM
    • HTML DOM은 HTML을 위한 접근하는 표준 방법과 객체들의 표준셋을 정의한다. 그리고 HTML document를 처리한다.
    • 모든 HTML element들은 그들에 포함된 text와 속성들과 함께 DOM을 통해 접근 할 수 있다.
  2. HTML DOM 객체들
    • HTML DOM 객체 종류
      • Anchor object
      • Document object
      • Event object
      • Form and Form Input object
      • Form, Frameset, and IFrame object
      • Image object
      • Location object
      • Navigator object
      • Option and Select object
      • Screen object
      • Table, TableHeader, TableRow, TableData object
      • Window object

Document 객체

  1. Write text to the output
    <html>
    <head>
    <script type="text/javascript">
        document.write("Hello World!");
    </script>
    </head>
    <body>
    </body>
    </html>
    
  2. Write text with Formatting to the output
    <html>
    <head>
    <script type="text/javascript">
        document.write("<h1>Hello World!</h1>");
    </script>
    </head>
    <body>
    </body>
    </html>
    
  3. Use getElementById()
    <html>
    <head>
    <script type="text/javascript">
        function getElement(){
            var x = document.getElementById("myHeader");
            alert("I am" + x.tagName + "element");
        }
    </script>
    </head>
    <body>
        <h1 id="myHeader" onclick="getElement()"> 
            Click to see what Element I am!
        </h1>
    </body>
    </html>
    
  4. 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>
    
  5. 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>
    
  6. 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>
    

Event 객체

  1. 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 thecursor.</p>
    </body>
    </html>
    
  2. 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 keypressed.</p>
    </body>
    </html>
    
  3. 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) 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>
    
  4. 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>
    

참고문헌

문서에 대하여

최초작성자 : [김민재]
최초작성일 : 2006년 10월 6일
버전 : 0.1
문서이력 :

  • 2006년 10월 6일 김민재 문서 최초 생성
  • 2007년 4월 2일 난다 문서 수정
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. 4월 02, 2007

    장회수 says:

    수고가 많아요~~~~ ^^

    수고가 많아요~~~~ ^^

  2. 4월 02, 2007

    Ryu Sung Hee says:

    멋지십니다~~~~

    멋지십니다~~~~

  3. 4월 10, 2007

    Anonymous says:

    번역된걸 보니까 접근하기가 쉬워서 좋네요..^^

    번역된걸 보니까 접근하기가 쉬워서 좋네요..^^