본문 바로가기

옛글/Database이야기

(XML)javascript 이해하기

반응형

Javascript란?

Javascript를 사용하면 웹 페이지에 프로그램을 삽입하여 이들 프로그램을 실행시킬 수 있다.

<head>

    <title>Welcome To JavaScript</title>

</head>

 

<body>

    <script language="javascript"> // 브라우저에게 어떤 스크립트 언어를 사용하고 있는지 알려줌

    <!--

        document.writeln("Welcome to JavaScript!") //코드의 표현식

    //--> // 코드내용이 직접 화면에 나타나지 않도록 html 주석문 내에 코드를 작성

    </script>

    <center>

        <h1>Welcome To JavaScript!</h1>

    </center>

</body>

 

</html> 

JavaScript는 객체를 기반으로 한다

JavaScript에서 객체를 통해 브라우저 또는 문서의 일부에 접근할 수 있다는 것을 의미한다

document.writeln("Welcome to JavaScript!")

document: 현재 웹 페이지 본문을 나타냄

writeln("write line") 메소드: 웹 페이지에 내용을 표시하는 등의 어떤 동작을 수행하도록 할 때 사용

 

JavaScript의 주요 객체들에 대한 내용을 소개

  • Document: 현재 웹 페이지의 본문을 나타낸다. 이 객체를 사용하면 링크, 이미지, 앵커 등과 같은 웹 페이지의 모든 구성요소에 접근할 수 있다
  • History: 웹 브라우저에서 현재 페이지를 열기 전까지의 사이트 기록을 가지고 있다. 이 객체를 사용하면, 히스토리 목록을 통해 이전 페이지 또는 다음 페이지로 이동할 수 있다
  • Location: 현재 웹 페이지의 위치에 대한 url, 도메인 이름, 경로, 서버 포트 등의 정보를 갖는다
  • Navigator: 실제로 브라우저 자체를 가리킨다 이 객체를 사용하면, 사용중인 브라우저의 종류를 알아낼 수 있다.
  • Window: 현재 브라우저 창을 가리키며, 여러 가지 강력한 메소드들을 제공한다

 

JavaScript에서 객체 속성과 메소드 사용하기

메소드를 사용하려면 객체의 이름에 마침표 (.) 를 붙이고 메소드의 이름을 붙여 사용 한다

  • Document.write: 현재 웹 페이지의 본문에 기록한다
  • Document.writeln: 현재 웹 페이지의 본문에 기록하고 텍스트의 끝에 캐리지 리턴(carriage return)을 붙인다
  • Write,writeln 의 차이점? Writeln이 pre 태그 안에서만 자동 줄 바꿈이 됨
  • History.go: 브라우저 히스토리 목록 중의 특정 위치로 이동하여 브라우저에 표시한다
  • Window.alert: 경고 대화 상자를 표시하게 만든다
  • Window.open: 새로운 브라우저 창을 열어서 새로운 문서를 표시할 수 있도록 한다

브라우저에 일정한 동작을 수행하도록 하는 메소드를 사용할 수 있을 뿐 아니라, 속성을 사용하면 JavaScript 객체의 설정 값들을 읽어들이거나 변경할 수 있다

객체들과 함께, 이들에 대한 속성의 몇 가지 예

  • Document.bgcolor: 현재 페이지의 배경색을 저장하고 있다
  • Document.fgcolor: 현재 웹 페이지의 전면색(텍스트 색깔)을 지정하고 있다
  • Document.lastmodified: 최근에 페이지가 수정된 날짜를 저장하고 있다
  • Document.title: 현재 페이지의 제목을 저장하고 있다
  • Navigator.appName: 브라우저의 실제 이름을 저장하며, 사용자가 어떠 ㄴ브라우저를 사용하고 있는지 확인하고자 할 때 사용한다

 

JavaScript에서 이벤트 사용하기

<head>

    <title>Using JavaScript Events</title>

</head>

 

<body onmousedown="document.bgColor='green'">

    <center>

        <h1>Click anywhere to turn this page green!</h1>

    </center>

</body>

 

</html> 

사용할 수 있는 이벤트의 종류

  • Onblur: 구성요소가 입력 초점을 잃어버릴 때 발생한다
  • Onchange: html 컨트롤 내에 데이터가 바뀔 때 발생한다
  • Onclick: 구성요소를 클릭할 때 발생한다
  • Ondblclick: 구성요소를 더블 클릭할 때 발생한다
  • Onerror: 코드를 실행하는 동안 오류를 만나게 되면 발생한다
  • Onfocus: 구성요소가 초점을 갖게 될 때 발생한다
  • Onkeydown: 키를 누를 때 발생한다
  • Onkeypress: 키를 누를 때 발생하며, 코드에서 입력된 키 코드값을 읽을 수 있다.
  • Onkeyup: 키를 눌렀다가 놓을 때 발생한다
  • Onload: 페이지가 브라우저에 처음으로 로드될 때 발생한다
  • Onmousedown: 마우스 버튼을 누를 때 발생한다
  • Onmousemove: 마우스가 이동할 때 발생한다
  • Onmouseout: 마우스가 화면에 보이는 html 구성요소를 떠날 때 발생한다
  • Onmouseover: 마우스 커서가 구성요소 위로 지나갈 대 발생한다
  • Onmove: 사용자 또는 코드에 의해, 구성요소가 이동될 때 발생한다
  • Onreset: 사용자가 html 폼의 reset 버튼을 클릭할 때 발생한다
  • Onresize: 코드 또는 사용자가 구성요소 또는 페이지의 크기를 조정할 때 발생한다
  • Onselect: 사용자가 선택을 할 때 발생한다
  • Onsubmit: 사용자가 html 폼의 전송(submit) 버튼을 클릭 할 때 발생한다
  • Onunload: 브라우저에서 페이지를 해체시킬 때 발생한다

 

JavaScript로 프로그래밍 하기

<head>

    <title>Using the JavaScript if Statement</title>

</head>

 

<body>

    <center>

        <h1>Using the JavaScript if Statement</h1>

    </center>

    <script language="javascript">

        if(719>143){

            document.writeln("the first value is greater than the second")

            }

    </script>

</body> 

 

JavaScript에서 데이터 사용하기

거의 모든 JavaScript 프로그램에서 기본적으로 데이터를 사용하며, JavaScript에서 데이터 값들은 변수에 저장된다

<head>

    <title>Using variable in javascript</title>

</head>

 

<body>

    <center>

        <h1>isomg varoables in javascript</h1>

    </center>

    <script language="javascript">

        var number

        temperature = 72 //temperature 라는 새로운 변수를 만들고, 대입연산자를 사용하여 72라는 값을 저장하고 있다

        document.writeln("the temperature is" + temperature + " degrees")

    </script>

</body> 

<head>

    <title>Using variable in javascript</title>

</head>

 

<body>

    <center>

        <h1>isomg varoables in javascript</h1>

    </center>

    <script language="javascript">

    <!--    

    var weatherReport

        weatherReport = "the temperature is 72 degrees"

        document.writeln(weatherReport)

    -->

    </script>

</body> 

 

JavaScript에 주석문 붙이기

<head>

    <title>Using variable in javascript</title>

</head>

 

<body>

    <center>

        <h1>isomg varoables in javascript</h1>

    </center>

    <script language="javascript">

    <!--

    //weatherReport 변수를 생성한다    

    var weatherReport

    //weatherReport에 값을 할당한다

        weatherReport = "the temperature is 72 degrees"

        //weatherReport의 값을 화면에 표시한다

        document.writeln(weatherReport)

    -->

    </script>

</body>

 

JavaScript 연산자 사용하기

<head>

    <title>using operators in javascript</title>

</head>

 

<body>

    <center>

        <h1>using operators in javascript</h1>

    </center>

    <script language="javascript">

        var result

        result = 219*45

        document.writeln("219*45=" + result)

    </script>

</body> 

 

JavaScript의 if 문 만들기

If(조건) { 코드 }

<head>

    <title>using the javascript if statement</title>

</head>

 

<body>

    <center>

        <h1>using the javascript if statement</h1>

    </center>

    <script language="javascript">

        var temperature

        temperature = 45

        if(temperature >32)

        {

            document.writeln("we're above freezing")

        }

    </script>

</body> 

 

JavaScript의 if…else 문 만들기

If(조건){ 조건이 참일 때 실행되는 코드 }

Else{ 조건이 거짓일 때 실행되는 코드 }

<head>

<title>using the javascript else clause</title>

</head>

 

<body>

    <center>

        <h1>using the javascript else clause</h1>

    </center>

    <script language="javascript">

        var temperature

        temperature = 5

        if(temperature > 32)

        {

            document.writeln("we're adove freezing")

        }

        else{

            document.writeln("time to drain the pool")

            }

            

    </script>

</body> 

 

Switch 문 만들기

여러 가지 경우를 검사하고자 할 때 사용한다

Switch(test){

Case value1:

……………….test가 value1과 일치할 때 실행되는 코드………………..

Break;

Case value2:

……………….test가 value2과 일치할 때 실행되는 코드………………..

Break;

Case value3:

……………….test가 value3과 일치할 때 실행되는 코드………………..

Break;

Default:

……………………..어떤 경우와도 일치하지 않을 때 실행되는 코드…………………….

Break;

}

<head>

<title>using the javascript else clause</title>

</head>

 

<body>

    <center>

        <h1>using the javascript else clause</h1>

    </center>

    <script language="javascript">

        var weatherReport

        userInput = "HELP"

        switch(userInput){

            case"EDIT":

                document.writeln("now entering EDIT mode")

                break;

            case"HELP":

                document.writeln("sorry, no help is available")

                break;

            case "QUIT":

                document.writeln("are you sure you want to quit?")

                break;

            default:

                document.writeln("i do not understand that response")

                break;

                }

                        

    </script>

</body> 

 

JavaScript의 for 루프문 만들기

루프를 사용하면 원하는 만큼 일정 코드를 반복하여 실행 할 수 있다

For(초기화; 검사; 증가값) { 코드 }

<head>

<title>using the for statement</title>

</head>

 

<body>

    <center>

        <h1>using the for statement</h1>

    </center>

    <script language="javascript">

        for(var loopIndex = 1; loopIndex<=10; loopIndex++){

            document.writeln("the loop index value is" + loopIndex + "<br>")

            }

    </script>

 

</body> 

 

While 루프문 만들기

루프가 실행될 때 마다 조건을 검사하여, 조건이 조건이 참이면 루프내의 코드를 실행한다

While(조건) {코드}

<head>

<title>Using the while statement</title>

</head>

 

<body>

    <center>

        <h1>using the while statement</h1>

    </center>

    <script language="javascript">

        var loopIndex = 0

        

        while(loopIndex < 10){

            loopIndex++

            document.writeln("the loop index value is" + loopIndex + "<br>")

            }

    </script>

</body>

 

Do…while 루프문 만들기

루프의 코드가 실행되고 난 끝부분에서 조건을 검사하는 것을 제외하고는 while 루푸와 매우 유사

Do{코드}

While(조건)

<body>

    <script language="javascript">

        var number =25

        do{

            document.writeln("the reciprocal of" +number+ " is" + 1/number+"<br>")

            --number

            } while(number>0)

        

    </script>

</body> 

JavaScript에서 함수 만들기

Function 함수-이름([인수1, [인수2, … 인수n]]]) {코드}

<head>

    <title>using javascript functions</title>

</head>

 

<body>

    <center>

        <h1>using javascript functions</h1>

    </center>

    <script language="javascript">

        document.writeln("the time is" + getTime()+ " right now")

        

        function getTime()

        {

            var now = new Date

            var returnValue = now.getHours() + ":" + now.getMinutes()

            return(returnValue)

        }

    </script>

</body> 

 

함수에 값 전달하기

함수에 전달하는 값들을 인수라고 한다

<body>

    <center>

        <h1>passing arguments to function in javascript</h1>

    </center>

    <script language="javascript">

        document.writeln("47+99 = " + adder(47,99))

        

        function adder(value1, value2)

        {

            return (value1+value2)

        }

    </script>

</body>

JavaScript 에서 객체 만들기

<body>

    <center>

        <h1>using javascript function</h1>

    </center>

    

    <script language="javascript">

        document.writeln("the time is " + getTime() + "right now")

        function getTime()

        {

            var now = new Date

            var returnValue = now.getHours() + ":" +now.getMinutes()

            return (returnValue)

        }

    </script>

 

</body> 

New 연산자는 date 클래스 생성자를 사용한다

생성자는 객체를 만들어서 되돌려 줄 때 클래스에서 사용하는 특수한 메소드를 가리킨다

 

JavaScript에서 String 객체 사용하기

텍스트 문자열을 저장할 수 있고, 이들 문자열에 대한 여러 가지 메소드들을 제공한다

<body>

    <center>

        <h1>using the string class

        </h1>

    </center>

    <script language="javascript">

        var string1 = new String("javascript and xml are a good mix")

        

        document.writeln("the text string, " +string1.italics()+" , is"+ string1.length+ "characters long")

    </script>

</body>

 

Array 클래스를 사용하여 배열 만들기

배열은 여러 데이터 항목들의 집합을 저장할 수 있는 프로그래밍 구조를 가리키며, 숫자 인덱스를 통해 각 항목들에 접근 할 수 있다.

<body>

    <center>

        <h1>using arrays in javascript</h1>

    </center>

    <script language="javascript">

        var scores = new Array()

        var runningSum = 0

        scores[0] = 43

        scores[1] = 87

        scores[2] = 92

        scores[3] = 70

        scores[4] = 55

        scores[5] = 61

        for(var loopIndex=0; loopIndex < scores.length; loopIndex++){

            runningSum += scores[loopIndex]

        }

        document.write("the average student score is" + runningSum / scores.length)    

    </script>

 

</body> 

 

이벤트 사용하기

<head>

<title>working with events in javascrip</title>

<script language="javascript">

    function displayMessage(e)

    {

        document.form1.Text.value = "welcome to event handling"

    }

</script>

</head>

 

<body>

    <center>

        <form name="form1">

            <h1>working with events in javascript</h1>

            <br />

            <h2>click the button!</h2>

            <br />

            <input type="text" name="Text" size="60" />

            <br /><br />

            <input type="button" value="click here" onclick="displayMessage()" />

        </form>

    </center>    

</body>

 

마우스 이벤트 처리하기

  • Onmousedown: 페이지에서 마우스 버튼이 눌려질 때 발생한다
  • Onmouseup: 페이지에서 눌려진 마우스 버튼을 놓을 때 발생한다

<head>

    <title>using javascript and the mouse</title>

    

    <script language="javascript">

        document.onmousedown = mouseDownHandler

        document.onmouseup = mouseUpHandler

        

        function mouseDownHandler(e)

        {

            if(navigator.appName == "Microsoft Internet Explorer"){

                document.form1.Text.value = "mouse button down at: " + window.event.x + ", " + window.event.y

            }

            if(navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4){

                document.form1.Text.value = "mouse button down at: " +e.pageX + " , " + e.pageY

            }

            if(navigator.appName == "Netscape" && parseInt(navigator.appVersion) > 4){

                document.form1.Text.value = "mouse button down at: " +e.clientX + " , " + e.clientY

            }

        }

            

            function mouseUpHandler(e)

            {

                if(navigator.appName == "Microsoft Internet Explorer"){

                    document.form1.Text.value = "mouse button up at: " + window.event.x + " ," + window.event.y

                }

                if(navigator.appName == "netscape" && parseInt(navigator.appVersion) == 4){

                    document.form1.Text.value = "mouse button up at:" + e.pageX + ", " + e.pageY

                }

                if(navigator.appName == "netscape" && parseInt(navigator.appVersion) > 4){

                    document.form1.Text.value ="mouse button up at:" + e.clientX + ", " + e.clientY

                }

            }

    </script>

</head>

 

<body onmousedown="mouseDownHandler(event)" onmouseup="mouseUpHandler(event)">

    <center>

        <form name="form1">

            <h1>using javascript and the mouse</h1>

            <br />

            click the mouse

            <br />

            <br />

            <br />

            <input type="text" name="Text" size="60" />

        </form>

        

    </center>

</body>

 

반응형