javascript (24)

 

둥근 토글 버튼

본 포스팅에서는 html, css, javascript를 이용하여 둥근 toggle버튼을 만들고, 버튼의 상태가 변경될 때마다 상태를 출력하는 기능까지 만들어 봅니다. 본 보스팅에 사용되는 기본코드는 w3schools에서 가지고 온 것입니다. w3schools에서는 단순히 css를 이용해서 토글버튼처럼 보이는 것을 만드는 것 까지만 보여주었는데, 저는 그렇게 토글이 될 때마다 자바스크립트를 이용해서 어떤 기능이 실행되는 부분까지 확장해서 포스팅합니다.

 

우선 toggle.html 파일에 input tag를 이용해서 아래와 같이 작성해줍니다.

<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <label class="switch">
        <input type="checkbox" />
        <span class="slider round"></span>
    </label>
</body>

</html>

 

그리고 toggle.css 파일을 하나 만들어서 그 안에 아래와 같이 작성을 해줍니다.

/* 슬라이더 외부를 감싸는 라벨에 대한 스타일 */
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

/* HTML 기본 체크박스 숨기기 */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* 슬라이더 - 실제로 토글될 부분 */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* 슬라이더를 동그랗게 보여주기 위한 부분 */
.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

 

이제 HTML 파일의 <head></head> 부분에 위 css 파일을 링크시켜줍니다.

<head>
	<link rel="stylesheet" type="text/css" href="toggle.css" />
</head>

 

이제 toggle.html 파일을 더블클릭해서 브라우저에서 열어보면 아래 영상처럼 움직이는 것을 확인할 수 있습니다.

 

둥근 토글 버튼 움직이는 영상

 

자, 이제 여기에 자바스크립트를 이용하여 기능을 추가해보도록 할건데요,

이 토글버튼은 input 태그의 checkbox를 이용한 것이므로 토글이 될 때마다 checked 속성이 변경되도록 되어있습니다.

이 기본적인 내용을 기억하고 자바스크립트에서 토글버튼의 checked 속성을 기반으로 특정 문자열을 출력하도록 해보겠습니다.

자바스크립트 파일은 따로 만들지 않고 그냥 html 파일에 추가하도록 할게요.

우선, input 태그에 onclick 속성을 이용하여 toggle이라는 함수를 호출하도록 하고, toggle 함수를 구현하겠습니다.

아래처럼 input  태그의 onclick 속성을 넣어주세요. 

<label class="switch">
    <input type="checkbox" onclick="toggle(this)">
    <span class="slider round"></span>
</label>

이렇게 해주면 토글버튼(체크박스)가 클릭될 때마다 toggle이라는 함수를 호출하면서 자기자신을 파라미터로 넘겨주게 됩니다.

 

자, 이제 body 아래쪽에 자바스크립트를 이용하여 스크립트를 작성해보겠습니다.

<script>
    function toggle(element) {
        console.log(element.checked);
    }
</script>

위 코드는 <head></head> 에 위치해도 되고 <body></body> 사이에 위치해도 됩니다.

당연히 별도 파일로 분리하여 작성해도 됩니다.

분리하여 작성하는 것과 관련해서는 제가 작성한 다른 포스트에서 확인 가능합니다. -> https://keichee.tistory.com/356

저는 <body></body> 사이에 넣어놓았습니다.

<body>
    <label class="switch">
        <input type="checkbox" onclick="toggle(this)">
        <span class="slider round"></span>
    </label>

    <script>
        function toggle(element) {
            console.log(element.checked);
        }
    </script>
</body>

 

자, 여기까지 html 파일 전체 코드가 어떻게 되는지 다시 한번 보여드릴게요.

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="toggle.css" />
</head>

<body>
    <label class="switch">
        <input type="checkbox" onclick="toggle(this)">
        <span class="slider round"></span>
    </label>

    <script>
        function toggle(element) {
            console.log(element.checked);
        }
    </script>
</body>

</html>

 

여기까지 완성하여 실행하면 체크박스(토글버튼)을 클릭할 때마다 toggle함수가 실행되면서 현재 체크박스의 상태가 어떻게 바뀌었는지를 출력하게 됩니다.

확인을 위해서 브라우저에서 toggle.html 파일을 새로고침하여 다시 열어주시고,

화면에서 우클릭 > 검사 (inspect)를 선택하여 개발자도구(developer tools)를 열어서 console탭을 열어주세요.

그리고 버튼을 누를때마다 어떤 값이 출력이 되는지 확인해보도록 하겠습니다.

 

토글 버튼 동작 영상

 

자, 이렇게 자바스크립트를 이용해서 토글버튼의 상태값을 출력해보았습니다.

어떤가요? 별로 어렵지 않죠? css 스타일을 해석하기 힘드실 순 있겠으나, 여기서 그런 부분을 자세하게 다루진 않겠습니다.

좀 더 나아가서 토글버튼의 상태값에 따라 ajax 요청을 서버에 날려 실제 DB를 업데이트하거나, 

또는 html의 특정 element를 hide하거나 show하는 등의 기능을 만들어 보세요.

 

그럼 오늘도 즐거운 코딩하시길 바래요 ^-^

 

- 깐깐한 개발자 -

JSP와 Javascript의 차이가 뭘까요? 라는 질문을 받은 적이 있습니다.

초보자 분들이 충분히 할만한 질문이죠. JSP도 자바스크립트도 제대로 사용해보기 전에는 두 가지가 뭐가 다른지 잘 모를 수 있습니다.

 

초보자 분들이 이해할 정도로 간략하고 쉽게 요점만 설명드리겠습니다.

 

Javascript웹브라우저(사용자의 컴퓨터)에서 실행이되는 스크립트 언어입니다.

자바스크립트 파일은 .js 확장자를 가지며, 자바스크립트 문법에 따라 작성을 해야합니다.

프로그래밍 언어 중 하나라고 생각하시면 됩니다.

반면, JSP는 Java Server Page의 약자로 .jsp 확장자를 가지며, 언어의 종류를 나타내는 것은 아닙니다.

.jsp 파일에는 html태그와 javascript 함수도 사용이 가능하며, 추가로 아래와 같이 <% java code %> 형태로 자바문법을 사용할 수 있습니다.

 

<html>

<head><title>Hello World</title></head>

<body> Hello World!<br/>

<% out.println("Your IP address is " + request.getRemoteAddr()); %>  <!-- 여기가 JSP 문법 -->

</body>

</html>

 

JSP에 작성된 내용은 서버에서 실행되고, 그 결과가 웹브라우저(사용자 컴퓨터)로 전송됩니다.

 

이제 JSP와 자바스크립트의 차이점이 뭔지 아시겠죠?

 

가시기 전에 공감 꾸~~~~욱 눌러주고 가세요 ^-^

💻 Programming/웹프로그래밍

[jQuery] 1. jQuery 시작하기

jQuery란 무엇인가?

jQuery 는 빠르고 정확한 JavaScript Library 입니다. John Resig이라는 사람이 2006년에 만들었다고 하네요. Write less, do more. 이게 jQuery가 탄생한 이유입니다. 적은코드로 많은 일을 하는 것. 

jQuery 는 HTML 문서 traversing, event handling, animating, and Ajax interactions 을 단순화 시켜줍니다.

jQuery의 특징에는 다음과 같은 것들이 있습니다.

  • DOM 조작: Sizzle이라는 selector엔진을 이용해서 DOM 요소를 선택하거나, 검색하거나, 요소의 내용을 수정하는 작업을 용이하게 해줍니다. 

  • Event handling: HTML코드를 사용하지 않고 이벤트 처리를 할 수 있게 해줍니다. 

  • AJAX 지원 

  • 애니메이션 : 상당히 많은 애니메이션 효과를 제공합니다.

  • 가볍다 : 19KB 정도 밖에 안되는 매우 가벼운 라이브러리 입니다. ( Minified and gzipped ).

  • 다양한 브라우저 지원 : IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+

  • 최신 기술 지원 : CSS3 selectors 와 basic XPath 문법을 지원합니다.

jQuery 설치하기

jQuery 설치하는 것은 어렵지 않습니다. 

  1. 최신버전 다운로드하기 : download jQuery  

  2. 다운로드한 최신버전의 jquery-x.y.z.min.js 파일을 프로젝트 경로 내에 넣어주세요, e.g. /jquery.

파일명에 min.js로 끝나는 버전은 최소화된 버전으로 불필요한 빈 줄이나 단어를 제외한 버전이라고 합니다.

 

 

jQuery 라이브러리 사용하기

 jquery 라이브러리 include하는 방법은 다음과 같습니다. 

<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript">
      // you can add our javascript code here 
   </script>   
</head>
<body>
........
</body>
</html>

jQuery 라이브러리 함수 호출하기

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded.

To do this, we register a ready event for the document as follows:

$(document).ready(function() {
   // do stuff when DOM is ready
 });

To call upon any jQuery library function, use HTML script tags as shown below:

<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   
   <script type="text/javascript" language="javascript">
   // <![CDATA[
   $(document).ready(function() {
      $("div").click(function() {
        alert("Hello world!");
      });
   });
   // ]]>
   </script>

</head>
<body>
<div id="newdiv">
Click on this to see a dialogue box.
</div>
</body>
</html>

 

 

사용자 정의 스크립트 사용하기

custom.js 파일에 내가 정의한 기능을 따로 정의합니다.

/* Filename: custom.js */
$(document).ready(function() {
  $("div").click(function() {
 alert("Hello world!");
  });
});

다른 페이지에서 custom.js 파일내에 정의된 기능을 실행하고자 할때에는 이 파일을 추가하면 됩니다

<html>
<head>
<title>The jQuery Example</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" 
   src="/jquery/custom.js"></script>
</head>
<body>
<div id="newdiv">
Click on this to see a dialogue box.
</div>
</body>
</html>

 

다른 라이브러리 동시 사용하기:

jQuery 를 다른 라이브러리와 함께 사용하게 되면 충돌가능성이 있을 수 있습니다. $ 기호를 다른 라이브러리에서도 사용할 수 있기 때문입니다.   

 

 $.noConflict() 메소드를 실행하면 $ 변수를 먼저 import한 라이브러리에 우선권을 넘기게 됩니다. jQuery에서 $는 단지 jQuery의 alias일 뿐이므로 $를 쓰지 않아도 전혀 문제될 것이 없습니다. 사용법을 한번 보시죠. 

// Import other library
// Import jQuery
$.noConflict();
// Code that uses other library's $ can follow here.

이 방법은 특히 .ready() 메소드의 기능과 쓰일때 강력하다고 하네요. jQuery의 $를 사용할 수 있게 해주기 때문이죠.  

사용법을 한번 보실까요? 

// Import other library
// Import jQuery
$.noConflict();
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.
DOM Element

 

 

 

 

Reference : http://www.tutorialspoint.com/jquery/jquery-overview.htm

 

 

 

 

 

웹애플리케이션을 개발할때 사용자의 브라우저가 무엇인지는 정말 중요한 요소이다. 만약 여러가지 브라우저에서 모두 정상적인 화면을 보여주려면 정말 많은 노력을 해야한다. 브라우저마다 화면에 보여지는 모습이 다를때가 많기 때문이다. 

오늘은 사용자의 브라우저가 무엇인지를 구분할 수 있게해주는 Navigator 객체에 대해서 알아보도록 하겠다.


Navigator 속성

네비게이터 객체의 속성은 아래와 같다. 

PropertyDescription
appCodeName브라우저 고유의 코드명에 대한 속성이다. 넷스케이프는 Netscape , 익스플로러는 Microsoft Internet Explorer 값을 가진다.
appVersion브라우저 버전, 언어, 호환성 등등의 정보를 갖는 속성이다.
language넷스케이프에서만 사용되는 속성이다. 언어코드를 두개의 케릭터로 갖는다. ko, en 처럼 말이다.
mimTypes[]클라이언트(브라우저)가 지원하는 모든 MIME 타입을 갖고있는 속성이다.역시 넷스케이프 전용이다.
platform[]브라우저의 플랫좀 정보를 갖는 속성이다."Win32" for 32-bit Windows operating systems
plugins[]브라우저에 설치된 모든 플러그인의 정보를 갖는 속성이다. 넷스케이프 전용이다.
userAgent[]코드명과 브라우저의 버전을 갖는 속성이다. 서버에서 클라이언트를 구분짓기위해 사용된다.

Navigator 메소드

다음은 Navigator에 특화된 메소드들입니다.

MethodDescription
javaEnabled()자바스크립트가 활성화된 클라이언트인지를 반환합니다. 브라우저에서 자바스크립트 실행을 금지했다면 false를 반환합니다.
plugings.refresh이 메소드는 새로 설치된 플러그인을 사용하도록 설정하고 모든 플러그인 목록에 추가합니다. Netscape only.
preference(name,value)서명된 스크립트가 넷스케이프의 속성값을 가져오거나 세팅할 수 있도록 해주는 메소드입니다. 두번째 인자가 없으면 getter의 역할을 하고 두번째 인자를 넣어주면 setter의 기능을 하게됩니다. Netscape only.
taintEnabled()데이타 tainting 의 활성화 여부를 참, 거짓으로 반환합니다. 


브라우저 구별하기

아래 소스를 브라우저 종류별로 테스트해보세요. 

<html>
<head>
<title>Browser Detection Example</title>
</head>
<body>
<script type="text/javascript">
<!--
var userAgent   = navigator.userAgent;
var opera       = (userAgent.indexOf('Opera') != -1);
var ie          = (userAgent.indexOf('MSIE') != -1);
var gecko       = (userAgent.indexOf('Gecko') != -1);
var netscape    = (userAgent.indexOf('Mozilla') != -1);
var version     = navigator.appVersion;

if (opera){
  document.write("Opera based browser");
  // Keep your opera specific URL here.
}else if (gecko){
  document.write("Mozilla based browser");
  // Keep your gecko specific URL here.
}else if (ie){
  document.write("IE based browser");
  // Keep your IE specific URL here.
}else if (netscape){
  document.write("Netscape based browser");
  // Keep your Netscape specific URL here.
}else{
  document.write("Unknown browser");
}
// You can include version to along with any above condition.
document.write("<br /> Browser version info : " + version );
//-->
</script>
</body>
</html>

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_browsers_handling.htm

 

 


JavaScript의 navigator 객체는 plugins 객체를 자식으로 갖고 있습니다. 이 객체는 배열의 구조를 가지고 있는데 브라우저에 설치되어있는 플러그인마다 각각 하나의 엔트리 포인트를 가지고 있습니다. navigator.plugins 객체는 Netscape, Firefox 그리고 Mozilla 에서만 지원합니다.

아래 예제는 브라우저에 설치되어있는 플러그인들의 목록을 모두 출력하는 예제입니다.  

<html>
<head>
<title>List of Plug-Ins</title>
</head>
<body>
<table border="1">
<tr>
    <th>Plug-in Name</th>
    <th>Filename</th>
    <th>Description</th>
</tr>
<script language="JavaScript" type="text/javascript">
for (i=0; i<navigator.plugins.length; i++) {
   document.write("<tr><td>");
   document.write(navigator.plugins[i].name);
   document.write("</td><td>");
   document.write(navigator.plugins[i].filename);
   document.write("</td><td>");
   document.write(navigator.plugins[i].description);
   document.write("</td></tr>");
}
</script>
</table>
</body>
</html>

 


플러그인 검사

각 플러그인은 배열에 하나의 엔트리를 가지고 있습니다. 각 엔트리는 다음과 같은 속성을 가지고 있습니다.

  • name - is the name of the plug-in.

  • filename - is the executable file that was loaded to install the plug-in.

  • description - is a description of the plug-in, supplied by the developer.

  • mimeTypes - is an array with one entry for each MIME type supported by the plug-in.

아래 예제를 한번 보실까요? 

<html>
<head>
<title>Using Plug-Ins</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
media = navigator.mimeTypes["video/quicktime"];
if (media){
  document.write("<embed src='quick.mov' height=100 width=100>");
}
else{
  document.write("<img src='quick.gif' height=100 width=100>");
}
</script>
</body>
</html>

video/quiktime 플러그인이 설치되어있는지를 검사한 뒤, 설치가 되어있으면 quick.mov를 embed하여 플레이 시킬 수 있도록 하였고 설치가 되어있지 않으면 quick.gif라는 이미지 파일을 보여주도록 하는 예제입니다. 

 


멀티미디어 다루기

대부분의 브라우저에서 동작하는 예제를 한번 보도록 할 까요???

<html>
<head>
<title>Using Embeded Object</title>
<script type="text/javascript">
<!--
function play()
{
  if (!document.demo.IsPlaying()){
    document.demo.Play();
  }
}
function stop()
{
  if (document.demo.IsPlaying()){
    document.demo.StopPlay();
  }
}
function rewind()
{
  if (document.demo.IsPlaying()){
    document.demo.StopPlay();
  }
  document.demo.Rewind();
}
//-->
</script>
</head>
<body>
<embed id="demo" name="demo"
    src="http://www.amrood.com/games/kumite.swf"
    width="318" height="300" play="false" loop="false"
    pluginspage="http://www.macromedia.com/go/getflashplayer"
    swliveconnect="true">
</embed>
<form name="form" id="form" action="#" method="get">
<input type="button" value="Start" onclick="play();" />
<input type="button" value="Stop" onclick="stop();" />
<input type="button" value="Rewind" onclick="rewind();" />
</form>
</body>
</html>

위 예제는  

http://www.amrood.com/games/kumite.swf 파일을 로딩해서 화면에 보여주는데,
Start버튼을 누르면 kumite.swf파일이 실행이 되면서 플래쉬게임이 진행이 되야 하는데,
제 브라우저에서는 동작을 안하네요? ㅋㅋ 왜 안되는지 이유를 밝혀서 올리도록 하겠습니다. ㅋㅋ
(embed태그의 play옵션을 true로 주면 실행이 되는데 아마 자바스크립트에서 실행하는 방법이
예제에 나와있는 것과 달라진것이 아닌가 싶네요.)

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

swf파일 실행시키는 거 한참 찾아봤는데도 잘 모르겠네요. UI쪽은 역시 힘들군요...아흑....

아시는 분 계시면 댓글좀 남겨주세요 ㅠㅠ 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_multimedia.htm

 

 

 


자, 이번에는 자바스크립트를 이용해서 화면에 애니메이션을 보여주는 방법을 한번 배워볼까요?

 

시작하기 전에 이미 자바스크립트 기반의 애니메이션을 위한 라이브러리가 존재한다는 것을 알고 넘어갑시다. ( Script.Aculo.us. )

이런 라이브러리를 사용하면 간편하게 애니메이션을 만들 수 있겠지만 그래도 어떤식으로 동작을 하는지는 알고넘어가야 나중에 본인이 이런 라이브러리를 수정해서 더 좋게 바꿀 수도 있습니다. 

 

그럼 시작해볼까요? 이번 포스팅에서는 기본적인 개념에 대해서 다룰 겁니다. 어떤 식으로 애니메이션이 완성이 되는지 말이죠. 

가장 많이 쓰이는 함수부터 확인을 해볼까요?  

  • setTimeout( 함수명, 밀리초) - 지정한 밀리초 후에 함수를 실행시킵니다. ( 함수가 종료된 뒤에 특정 시간이 지나면 다시 함수를 실행시킵니다. ) 

  • setInterval( 함수명, 밀리초) - 지정한 밀리초가 지날 때마다 한번씩 함수를 실행시킵니다. ( 실행시킨 함수가 끝나지 않아도 특정 시간이 지나면 또 실행시킵니다. ) 

  • clearTimeout( setTimeout() 함수의 변수 ) - setTimeout() 함수의 변수의 타이머를 클리어시킵니다. ( 무슨 말인지는 예제를 보면 이해가 가실겁니다. ) 

본격적으로 시작하기 전에 DOM 객체의 속성을 이용해서 특정 객체의 위치를 조정할 수 있다는 것을 알고넘어가시면 좋을 것 같습니다. top 이나 left 같은 속성을 줄 수 있는거죠. 간단한 문법은 다음과 같습니다.

// Set distance from left edge of the screen.
object.style.left = distance in pixels or points; 

or
// Set distance from top edge of the screen.
object.style.top = distance in pixels or points; 

수동적 애니메이션

이번 예제는 버튼을 누르면 이미지를 오른쪽으로 10픽셀씩 움직여주는 예제입니다. 버튼을 누르면 moveRight()함수를 호출을 하는데 이 함수는 imgObj.style.left를 이용해서 왼쪽에서 얼마나 떨어져 있는지를 지정해줍니다. init()에서는 left의 초기값을 지정해주는데 이 초기값을 숫자로 변환한다음 10을 더한값을 다시 left에 넣어주고 있네요. 즉, 초기위치에서 계속 10씩 더해지는 함수가 되는 것입니다. 이해가 안되시면 init()에서 left의 숫자를 변경해준다음 moveRight()에서 parseInt(...)부분을 빼고 그냥 10 + 'px'만 left에 할당해줘 보세요. 

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">

var imgObj = null;
function init(){
   imgObj = document.getElementById('myImage');
   imgObj.style.position= 'relative'; 
   imgObj.style.left = '0px'; 
}
function moveRight(){
   imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init; 

</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>
</html>

위 예제에 대한 단계적 실행은 아래와 같습니다. 

  • 자바스크립트의 getElementById() 함수를 이용해서 DOM 객체를 얻어옵니다. 여기서는 이미지가 되겠죠. 그렇게 얻어온 객체를 imgObj 변수에 할당합니다.  

  • Window가 로드될 때 init() 함수가 실행이 되면서 imgObj 객체의 positionleft 속성을 초기화 해줍니다. 

  • 그리고 버튼이 화면에 생성이 되고, 이 버튼이 클릭이 되는 순간 moveRight() 함수가 호출되면서 left 거리가 10 픽셀 증가하게 됩니다. 이 숫자에 마이너스 부호를 붙이면 반대쪽으로 움직이게 됩니다.

자동 애니메이션

위에서는 버튼을 클릭했을 때 움직이도록 했지만 이번에는 시간에 따라서 움직이도록 해보겠습니다. 제일 처음에 설명드린 세가지 함수들 중에서 setTimeout() 함수를 이용하는 예제입니다.

<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">

var imgObj = null;
var animate ;
function init(){
   imgObj = document.getElementById('myImage');
   imgObj.style.position= 'relative'; 
   imgObj.style.left = '0px'; 
}
function moveRight(){
   imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
   animate = setTimeout(moveRight,20); // 20 밀리초 마다 moveRight 함수 호출
}
function stop(){
   clearTimeout(animate);
   imgObj.style.left = '0px'; 
}
window.onload =init;

</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>

이번에는 시작과 종료버튼 두개가 생겼고 시작버튼을 누르면 moveRight()함수가 호출이 되는데 첫번째 예제에서 쓰였던 moveRight()과는 조금 다르네요 그쵸? 한줄이 더 생겼습니다. animate변수에 setTimeout(moveRight, 20)을 할당해주었네요. setTimeout 함수를 이용해서 moveRight함수를 20밀리초 마다 실행을 시키고 있습니다.

 

마우스 이벤트를 이용한 애니메이션

아래 예제는 마우스가 특정 이미지 위에 올라갔을 때 이미지를 다른 이미지로 변경해주는 것입니다. 

<html>
<head>
<title>Rollover with a Mouse Events</title>
<script type="text/javascript">

if(document.images){
    var image1 = new Image();      // Preload an image
    image1.src = "/images/html.gif";
    var image2 = new Image();      // Preload second image
    image2.src = "/images/http.gif";
}

</script>
</head>
<body>
<p>Move your mouse over the image to see the result</p>
<a href="#" onMouseOver="document.myImage.src=image2.src;"
            onMouseOut="document.myImage.src=image1.src;">
<img name="myImage" src="/images/html.gif" />
</a>
</body>
</html>

위 소스가 실행되는 순서를 한번 볼까요? 

  • 페이지가 로딩될 때 if 문에서 이미지 객체가 존재하는지 검사합니다. 이미지 객체가 존재하면 블락내의 명령을 실행하지만 존재하지 않으면 실행하지 않습니다.

  • Image() 생서자를 이용해서 2개의 이미지 객체를 생성하고 각각의 이미지 소스를 지정해줍니다.

  • <a>에서 # (hash mark) 는 링크를 없애주는 역할을 합니다. 클랙했을 때 특정 URL로 가려는 시도를 안하게 됩니다.

  • onMouseOver 이벤트 핸들러는 마우스가 링크(이미지) 위에 올라올 때 이벤트를 발생시키는 속성입니다. 그리고 반대로  onMouseOut 이벤트 핸들러는 마우스가 링크(이미지)밖으로 나갈 때 이벤트를 발생시킵니다.

 

직접 테스트해보고 이것저것 바꿔서도 해보세요. 그래야 실력이 생깁니다. 개발자로서의 힘이 생기는 거죠.

게임케릭터한테 아이템만 사주지 말고 여러분의 힘을 길러보세요. 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_animation.htm

 

 

 

 

유효성 검사라는 말은 좀 어렵죠? 간단히 말하면 그냥 검사하는겁니다. 보내려는 데이타가 제대로 된 포맷으로 전달이 되는지 아니면 필수 입력값이 빈칸으로 남아있지는 않은지 등등을 말이죠.
자 바스크립트에서 유효성 검사는 ​크게 두가지로 나눕니다. 기본 검사와 포맷검사. 기본검사에서는 필수입력값이 빈칸으로 남아있지는 않은지에 대한 검사를 합니다. 그리고 포맷검사에서는 입력한 데이타의 포맷이 서버에서 필요로 하는 포맷이 맞는지를 검사를 하게 됩니다.

 

예제를 한번 볼까요?? 검사를 할때는 아래처럼 코딩을 하게 됩니다. 검사를 할 때 하나의 텍스트필드 단위로 할 수도 있을 것이고 모든 필드를 대상으로 검사를 진행할 수도 있을텐데 이건 개발자의 재량껏 어떤식으로 구현하겠다~라고 정하면 될 것 같네요. 

<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
 <form action="/cgi-bin/test.cgi" name="myForm"  
          onsubmit="return(validate());">
 <table cellspacing="2" cellpadding="2" border="1">
 <tr>
   <td align="right">Name</td>
   <td><input type="text" name="Name" /></td>
 </tr>
 <tr>
   <td align="right">EMail</td>
   <td><input type="text" name="EMail" /></td>
 </tr>
 <tr>
   <td align="right">Zip Code</td>
   <td><input type="text" name="Zip" /></td>
 </tr>
 <tr>
 <td align="right">Country</td>
 <td>
 <select name="Country">
   <option value="-1" selected>[choose yours]</option>
   <option value="1">USA</option>
   <option value="2">UK</option>
   <option value="3">INDIA</option>
 </select>
 </td>
 </tr>
 <tr>
   <td align="right"></td>
   <td><input type="submit" value="Submit" /></td>
 </tr>
 </table>
 </form>
 </body>
 </html>


기본검사:

위에서 본 기본 틀에서 validation하는 기능을 구현해보았습니다.:

<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
 
   if( document.myForm.Name.value == "" )
   {
     alert( "Please provide your name!" );
     document.myForm.Name.focus() ;
     return false;
   }
   if( document.myForm.EMail.value == "" )
   {
     alert( "Please provide your Email!" );
     document.myForm.EMail.focus() ;
     return false;
   }
   if( document.myForm.Zip.value == "" ||
           isNaN( document.myForm.Zip.value ) ||
           document.myForm.Zip.value.length != 5 )
   {
     alert( "Please provide a zip in the format #####." );
     document.myForm.Zip.focus() ;
     return false;
   }
   if( document.myForm.Country.value == "-1" )
   {
     alert( "Please provide your country!" );
     return false;
   }
   return( true );
}
//-->
</script>

소스를 실행해보세요 ^__^

 

포맷검사:

 이번에는 포맷검사를 해보도록 할텐데요 이 포맷검사는 어떤 입력창에 들어와야 하는 입력값의 포맷을 정의하는 정책이 있어야 합니다. 예를들어 이메일을 입력해야하는 입력란에는 asdf@bbc.com과 같은 형태의 이메일 포맷을 갖고있는 문자열이 들어가야 한다는 것입니다. 아래 예제는 이메일 필드에 입력된 값이 이메일 형식에 맞는지를 검사해주는 기능이네요.

<script type="text/javascript">
<!--
function validateEmail()
{
 
   var emailID = document.myForm.EMail.value;
   atpos = emailID.indexOf("@");
   dotpos = emailID.lastIndexOf(".");
   if (atpos < 1 || ( dotpos - atpos < 2 )) 
   {
       alert("Please enter correct email ID")
       document.myForm.EMail.focus() ;
       return false;
   }
   return( true );
}
//-->
</script>

직접 테스트 해보실거죠?? ^___^

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_form_validations.htm

 

 

 


프로그래밍에는 세가지 종류의 에러가 있습니다.

 (a) 문법에러 (b) 런타임 에러 (c) 논리적 에러

문법 에러

문법에러는 파싱에러라고도 합니다. 문법상 맞지 않아서 발생하는 에러죠. 문법에러는 컴파일시에 에러가 있다고 알려주기때문에 찾기쉬운 에러입니다.

아래 예제는 닫는 괄호를 빼먹은 문법에러입니다.

<script type="text/javascript">
<!--
window.print(;
//-->
</script>

 

런타임 에러

런타임에러는 예외라고도 하며 실행시에 에러가 발생합니다. 아래 예제는 문법은 어긋나지 않지만 실행시에 오류가 발생합니다. 왜냐하면 존재하지 않는 메소드를 호출하려고 하기 때문이죠.

<script type="text/javascript">
<!--
window.printme();
//-->
</script>

 

논리적 에러

논리적으로 에러가 발생한 것은 찾기가 힘든 에러입니다. 문법적으로도 맞고 실행시에 아무런 문제가 발생하지 않지만 원하는 값이 안나오는 그런 에러이기 때문에 내가 구현한 로직이 잘못되어서 발생하는 에러라고 보시면 됩니다.

try...catch...finally

자바에서 쓰는 try-catch절을 자바스크립트에서도 쓸 수가 있네요
<script type="text/javascript">
<!--
try {
    // Code to run
    [break;]
} catch ( e ) {
    // Code to run if an exception occurs
    [break;]
}[ finally {
    // Code that is always executed regardless of 
    // an exception occurring
}]
//-->
</script>

 

예제:

존재하지 않는 함수를 호출할 경우 어떻게 에러가 발생하는지 한번 볼까요? 에러는 브라우저별로 다른게 보일 수 있다는 것을 명심하세요. 

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;

alert("Value of variable a is : " + myFunc2() );

} //--> </script> </head> <body> <p>Click the following to see the result:</p> <form> <input type="button" value="Click Me" onclick="myFunc();" /> </form> </body> </html>

 

 

이제 try...catch 절을 이용해서 에러를 잡아보도록 하죠.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   
   try {
      alert("Value of variable a is : " + myFunc2() );
   } catch ( e ) {
      alert("Error: " + e.description );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

finally 는 try-catch절에서 에러가 발생하든 안하든 항상 실행이 되는 부분입니다.

<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   
   try {
      alert("Value of variable a is : " + myFunc2()  );
   }catch ( e ) {
      alert("Error: " + e.description );
   }finally {
      alert("Finally block will always execute!" );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

throw

throw역시 자바에 있는 개념이죠. 예외가 발생했을 때 내가 처리안하고 다른녀석한테 처리해달라고 던지는 놈입니다. throw의 사전적 의미가 "던지다" 입니다. 아래 예제를 한번 보죠.
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
   var a = 100;
   var b = 0;
   
   try{
      if ( b == 0 ){
         throw( "Divide by zero error." ); 
      }else{
         var c = a / b;
      }
   }catch ( e ) {
      alert("Error: " + e );
   }
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

b에 0을 할당하고 b가 0이면 throw 하도록 만든 예제네요. throw가 어떤 식으로 화면에 표현되는지 한번 실행해보세요. 

 

onerror() 메소드

 onerror 메소드는 JavaScript에서 에러핸들링을 위해서 제일 처음 나온 기능이라고 합니다.  error 이벤트는 웹페이지에서 에러가 발생했을때 window객체에서 발생시킵니다. 아래 예제를 한번 볼까요.

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function () {
   alert("An error occurred.");
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

에러가 발생하면 경고창을 띄우도록 해놓고 존재하지 않는 함수를 호출하는 예제군요.

한번 실행해보세요. 

 

 onerror 이벤트 핸들러는 세가지 정보를 제공합니다.

  • 에러메시지 . 브라우저가 보여주는 에러메시지입니다.

  • URL . 에러가 발생한 파일을 알려줍니다.

  • 라인 넘버 . 에러를 발생시킨 라인이 몇번째 라인인지를 알려줍니다.

이 세가지 정보를 어떻게받아오는지 한번 볼까요?

<html>
<head>
<script type="text/javascript">
<!--
window.onerror = function (msg, url, line) {
   alert("Message : " + msg );
   alert("url : " + url );
   alert("Line number : " + line );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

 

 

 

 onerror 메소드는 아래와같이 이미지를 불러올때 에러가 발생하면 메시지를 보여주기 위해서 사용될 수도 있습니다.

<img src="myimage.gif"
    onerror="alert('An error occurred loading the image.')" />

 

이 onerror메소드는 이미지 태그 이외에도 다른 태그에서도 사용될 수 있다는 것을 알아두시면 좋을 듯 싶네요.

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_error_handling.htm 

 

 

 

 


이번 포스트에서는 자바스크립트의 객체에 대해서 알아볼텐데요 객체가 무엇인지는 알고계신다는 전제하에 실무 위주의 내용을 얘기해보도록 할거에요. 자바의 객체와 동일한 것이라고 생각하시면 되고 단지 사용법이 어떤지에 대해서 알고 넘어가는 정도로 습득하시면 될것 같습니다. 

객체의 속성

자바를 공부해 보신분들이라면 아시겠지만 객체 안에는 프리미티브 멤버변수나 다른 객체를 하나의 변수처럼 가지고 있습니다. 이런 멤버변수들을 자바스크립트에서는 속성이라고 얘기를 합니다. 그리고 그 속성들에 값을 넣는 방법은 다음과 같습니다.:
객체명.속성명 = 속성값;

예제:

아래 예제는 document객체의 title이라는 속성을 str변수에 할당하는 예제입니다. 

var str = document.title;

객체의 메소드

이번에는 메소드에 대해서 알아보죠.

예제:

아래 예제는 document객체 내부에 선언되어있는 write()메소드를 호출하는 예제입니다. 이미 여러번 보셨을 겁니다. hello world 뭐 이런 예제에서 말이죠.

document.write("This is test");


사용자 정의 객체

다 아시겠지만 모든 사용자정의 객체와 이미 정의되어있는 built-in 객체들은 Object라는 객체의 하위 클래스들입니다.

The new Operator:

아래 예제는 new 오퍼레이터를 이용해서 built-in JavaScript 객체들을 생성하는 것을 보여주고있습니다.

var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");


Object() 생성자:

생성자라는 것은 객체를 생성하고 초기화하는 메소드입니다. 위 예제에서 new Object(); 의 Object()는  Object객체의 생성자입니다. 이렇게 생성된 객체에 대한 레퍼런스를 var로 선언한 employee에 할당해주면 나중에 이 객체에 접근할 때 employee라는 이름으로 접근할 수 있습니다. 만약 employee가 이름과 나이를 속성으로 가지고 있다고 한다면 이런 것은 어떻게 값을 넣을 수 있을 까요? 속성은 변수가 아닙니다. 따라서 var키워드로 선언을 하지 않습니다. 아래 예제를 한번 보도록 하죠. 

예제 1:

아래 예제는 객체를 생성하고 그 객체의 속성을 정의해줍니다.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Create the object
    book.subject = "Perl"; // Assign properties to the object
    book.author  = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

 

 

예제 2:

이번 예제는 사용자 정의 객체를 만드는 예제입니다. 여기서 this 키워드는 함수로 전달된 객체를 참조하는 역할을 합니다.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
    this.title = title; 
    this.author  = author;
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

 

 

객체의 메소드 정의하기

이번에는 객체의 메소드를 정의하는 방법을 알아보도록 하겠습니다.

예제:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// 객체의 메소드가 될 함수를 정의합니다.
function addPrice(amount){
    this.price = amount; 
}

function book(title, author){
    this.title = title; 
    this.author  = author;
    this.addPrice = addPrice; // 메소드를 속성으로 할당(선언)합니다.
}

</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

 

 

with 키워드

with 키워드는 객체의 속성이나 메소드를 참조하기위한 단축키워드 같은 것입니다.

with에 파라미터로 전달된 객체는 해당 블락내에서 기본적인 참조변수처럼 동작합니다.따라서 해당 객체의 속성이나 메소드에 접근할 때 궂이 해당 객체이름과 점을 안찍어도 됩니다.

문법:

with (object){
    properties used without the object name and dot
}

예제:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    with(this){
       price = amount; 
    }
}
function book(title, author){
    this.title = title; 
    this.author  = author;
    this.price = 0;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   myBook.addPrice(100);
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
   document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>

 

 

 

 

 

 Reference : http://www.tutorialspoint.com/javascript/javascript_objects.htm 

 

 

 


이번에는 void 키워드에 대해서 한번 알아보도록 할까요?  

자바스크립트에서 사용되는 void는 자바의 void와 별반 다를게 없어보입니다.

우선 제가 조사한 바에 의하면 void의 역할을 아래와 같습니다.

void keyword evaluates the expression and always returns undefined.

한마디로 "표현식을 평가하고 항상 undefined를 반환한다"네요. 이게 무슨 말일까요? 아시는 분은 댓글좀 남겨주세요 ㅎㅎ   

사실 포스팅은 하는데 이게 도대체 언제 어떻게 쓰이는지에 대해서는 저도 잘 모르겠습니다. 어쨌든 이런 것도 있구나 하시면서 보시면 되겠습니다. 

일단 예제를 한번 보는게 낫겠죠?  

아래에 기본적인 예제가 나와있네요.

 

<head>
<script type="text/javascript">
<!--
void func()
javascript:void func()

or:

void(func())
javascript:void(func())
//-->
</script>
</head>

예제 1:

void 키워드가 가장 많이 사용되는 곳은 클라이언트 사이드의 javascript: URL​ 이라고 하네요. 이 예제에서는 alert함수를 사용했는데요

한번 실행시켜 보세요. void ( )를 없애고 그냥 alert('Warning!!!')만 써도 결과는 똑같이 나옵니다. 차이가 뭔지 저도 아직 잘 모르겠네요. 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(alert('Warning!!!'))">Click me!</a>
</body>

 

 

 

예제 2:

이번 예제에서는 void( )안에 "0" 만 써넣었네요. 사실 저도 이게 정확히 뭘 의미하는지 잘은 모르겠지만 제가 참조한 사이트에 의하면 다음처럼 얘기하고 있습니다. Here the expression "0" is evaluated but it is not loaded back into the current document. 0 이라는 값이 평가가 되기는 하는데 현재문서로 load되지는 않는다고 말이죠. 자, 결과가 예제 1과 뭐가 다른가요? 링크를 눌러도 아무런 변화가 안보이죠? 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript:void(0))">Click me!</a>
</body>

 

 

예제 3:

이번 예제에서는 void 키워드를 사용함으로써 고의적으로 undefined 값을 a에 할당하고 있습니다. 뭐 실제로 이렇게 쓸만한 일은 없을 것 같지만 이런 예제도 있구나 하시면 될 것 같네요. 

<head>
<script type="text/javascript">
<!--
function getValue(){
   var a,b,c;

   a = void ( b = 5, c = 7 );
   document.write('a = ' + a + ' b = ' + b +' c = ' + c );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</body>

 

 

 

예제 4:

마지막 예제입니다. 이번 예제에서는 void( )안에서특정 변수에 값을 할당하고 할당된 값을 경고창을 이용해서 뿌려주고있습니다.

사실 void키워드가 없어도 결과는 동일하게 나옵니다만....도대체 왜 void키워드를 쓰는지는 모르겠네요 ㅎㅎ;;;; 

<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<a href="javascript: void(myNum=10);alert('myNum = '+myNum)">
Set myNum Please</a>
</body>

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_void_keyword.htm

 

 

 

자바스크립트는 세 종류의 다이얼로그 박스를 제공합니다. 어떤 것들이 있는지 한번 볼까요??  

경고

사용자에게 경고메시지를 보여줄 때 사용하는 박스죠. 필수값을 입력하지 않고 진행하려는 사용자에게 경고를 할 때 주로 사용합니다. 

 

<head>
<script type="text/javascript">
<!--
   alert("Warning Message");
//-->
</script>
</head>

경고창은 OK버튼 하나만 가지고 있습니다. 뭔가를 알려주고 알겠다는 말을 해주고 사용자가 그 말을 확인했다는 확인버튼만 있는거죠. 


확인

확인창은 사용자에게 정말 실행하겠습니까? 와 같은 질문을 하고 확인을 하기 위해서 사용됩니다.그래서 버튼이 두개가 있죠. 확인버튼과 취소버튼이요.

사용자가 확인버튼을 누르면 confirm() 메소드는 참을 반환하고 취소버튼을 누르면 거짓을 반환합니다.그리고 거기에 따라서 어떠한 로직을 태울지는 개발자가 결정하면 되는거죠.

 

<head>
<script type="text/javascript">
<!--
   var retVal = confirm("Do you want to continue ?");
   if( retVal == true ){
      alert("User wants to continue!");
   return true;
   }else{
      alert("User does not want to continue!");
   return false;
   }
//-->
</script>
</head>

 


프롬프트

프롬프트 창은 사용자로부터 어떤 입력을 받을 수 있는 창입니다. prompt() 메소드를 사용하며 두개의 파라미터를 받습니다. 프롬프트창의 라벨과 창에 표시될 텍스트. 역시 버튼은 확인과 취소 두개의 버튼이 있습니다. 확인버튼을 누르면 prompt() 메소드는 입력된 값을 반환하고 취소버튼을 누르면 null을 반환합니다.


<head>
<script type="text/javascript">
<!--
   var retVal = prompt("Enter your name : ", "your name here");
   alert("You have entered : " +  retVal );
//-->
</script>
</head>

 

 직접 테스트 해보세요. 연습은 10번씩 해야 손에 익고 눈에 익고 실력으로 남습니다. 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_dialog_boxes.htm

 


기본적인 페이지 리디렉션

간단한 페이지 리디렉션은 아래처럼 하시면 되요~

<head>
<script type="text/javascript">
<!--
   window.location="http://www.newlocation.com";
//-->
</script>
</head>

 

 


리디렉션 메시지를 보여주고 특정 시간 후에 리디렉션하기

<head>
<script type="text/javascript">
<!--
function Redirect()
{
    window.location="http://www.newlocation.com";
}

document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

여기서 사용된 setTimeout() 메소드는 JavaScript에서 기본으로 제공하는 메소드로 특정 시간 후에 다른 함수를 호출할 수 있게끔 해줍니다.

 


브라우저 종류에 따른 리디렉션

<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName; 
if( browsername == "Netscape" )
{ 
   window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
   window.location="http://www.location.com/ie.htm";
}
else
{
  window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_page_redirect.htm

 

 

 


이번에는 쿠키를 다루는 방법에 대해서 알아보도록 하겠습니다. ^___^

Cookies 만들기

문법부터 보도록 하겠습니다.
document.cookie = "key1=value1;key2=value2;expires=date";

여기서 expires 속성은 옵션입니다. 쿠키의 생명주기를 지정해주는 속성이죠. 지정된 시일이 지나면 쿠키는 더이상 유효하지 않게됩니다.

Note: 쿠키 값은 세미콜론이나 쉼표 또는 스페이스를 포함할 수 없습니다. 그래서 저장하기 전에 escape() 함수를 이용해서 인코딩한 값을 이용하기도 하죠. escape()함수로 인코딩해서 저장을 했을 때는 unescape() 함수를 이용해서 decode해야 쿠키값을 제대로 읽어올 수 있습니다.

 

 

아래 예제는 input쿠키에 customer의 이름을 저장하는 것을 보여주고있습니다.

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   if( document.myform.customer.value == "" ){
      alert("Enter some value!");
      return;
   }

   cookievalue= escape(document.myform.customer.value) + ";";
   document.cookie="name=" + cookievalue;
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>

Cookies 읽기

​자바스크립트에서 쿠키는 document.cookie 객체라는 것은 위에서 알게되셨을겁니다. 쿠키에는 key, value페어가 여러개가 들어가있을 수 있습니다. 그리고 key와 value는 각각 세미콜론으로 구분이 되어집니다. 따라서 쿠키를 읽을때는 split() 함수를 사용하게 됩니다.

 

 

예제를 한번 보시죠.

<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
   var allcookies = document.cookie;
   alert("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);
   }
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>

 

 

위 소스는 여러분 컴퓨터에 저장된 쿠키를 읽어들여서 키, 값 페어를 화면에 출력하게됩니다. 

직접 한번 실행해 보세요~~ ^__^ 

Cookies 만료일자 설정하기

예제로 배워봅시다~~ 아래 예제는 쿠키의 만료일자를 1달뒤로 설정하는 코드입니다.

 

<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() + 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

Cookie 삭제하기

삭제를 하는 것은 실제로 삭제를 하는것이 아니라 단지 만료일자를 과거일자로 세팅하는 것입니다.

아래 예제를 보실까요?


<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
   var now = new Date();
   now.setMonth( now.getMonth() - 1 ); 
   cookievalue = escape(document.myform.customer.value) + ";"
   document.cookie="name=" + cookievalue;
   document.cookie = "expires=" + now.toUTCString() + ";"
   alert("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_cookies.htm 

 

 

 


Event 란?

이벤트가 뭘까요? 이벤트는 어떤 동작이라고 생각하시면 됩니다. 웹브라우저를 사용하는 사용자가 또는 웹브라우저가 어떤 동작을 하는 것을 이벤트라고 합니다. 생일파티나 축하이벤트 같은 그런 것과 혼동하시면 안됩니다 ㅋㅋㅋ

 

가장 흔하게 쓰이는 이벤트는 클릭입니다. 사용자가 어떤 버튼을 클릭하는 것. 이것도 하나의 이벤트이죠.

그럼 온클릭 이벤트에 대해서 한번 살펴볼까요? 

onclick 예제

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
   alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

 

위 소스는 화면에 버튼을 하나 생성합니다. 그리고 그 버튼을 누르면 sayHello()함수를 호출하게 됩니다.

 

onsubmit 예제

onclick 이벤트 다음으로 많이 쓰이는게 아마 onsubmit이벤트일겁니다. 이 이벤트는 폼 태그에서 사용자가 submit하게 되면 발생하는 이벤트죠.

  

<html>
<head>
<script type="text/javascript">
<!--
function validation() {
   // 유효성 검사를 여기다가 하시면됩니다.
   .........
   return true  // or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>

 

위 소스를 분석해보면...음...submit버튼이 있고 submit버튼이 눌릴때 return validate()를 하는데 이는 validate()에서 받은 결과를 반환하겠다는 의미입니다.


onmouseover 와 onmouseout:

이 이벤트들은 마우스가 화면의 특정 지역 안에 있는지 또는 특정 지역 안에 있다가 밖으로 나갔는지를 체크하여 특정 기능을 수행할 수 있도록 도와줍니다.

예제를 한번 살펴보죠.

 

<html>
<head>
<script type="text/javascript">
<!--
function over() {
   alert("Mouse Over");
}
function out() {
   alert("Mouse Out");
}
//-->
</script>
</head>
<body>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>

 

마우스가 <div>태그 내의 내용물 ( 화면에 보여지는 ) 위에 있으면 over()함수를 호출하고 밖으로 나가면 out()함수를 호출합니다. 

 

HTML 4 표준 이벤트

아래는 표준 이벤트들의 목록입니다. 위에서 해본것을 바탕으로 이런저런 기능드을 한번 테스트 해보세요~~ ^___^

 

EventValueDescription
onchangescriptScript runs when the element changes
onsubmitscriptScript runs when the form is submitted
onresetscriptScript runs when the form is reset
onselectscriptScript runs when the element is selected
onblurscriptScript runs when the element loses focus
onfocusscriptScript runs when the element gets focus
onkeydownscriptScript runs when key is pressed
onkeypressscriptScript runs when key is pressed and released
onkeyupscriptScript runs when key is released
onclickscriptScript runs when a mouse click
ondblclickscriptScript runs when a mouse double-click
onmousedownscriptScript runs when mouse button is pressed
onmousemovescriptScript runs when mouse pointer moves
onmouseoutscriptScript runs when mouse pointer moves out of an element
onmouseoverscriptScript runs when mouse pointer moves over an element
onmouseupscriptScript runs when mouse button is released

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_events.htm 

 

 


이번에는 자바스크립트의 함수에 대해서 알아보도록 하겠습니다.  

함수가 뭐냐? 모르시는 분이 계시려나요? 자바나 C의 메소드, 함수랑 똑같은 겁니다.

함수는 function 키워드를 이용해서 정의하는데 function의 영어 의미를 찾아보면 다음과 같습니다.

1.명사 (사람사물의) 기능
2.명사 행사, 의식
3.동사 (제대로) 기능하다[작용하다] (=operate)

따라서 함수는 특정 기능을 하는 놈이구나~ 라고  이해하시면 됩니다.

내가 원하는 어떤 기능을 하도록 만드는 것이죠.

 

자, 그럼 문법을 한번 살펴보겠습니다.

<script type="text/javascript">

function 함수명( 파라미터 리스트 )
{
  // statements
}

</script>

 

 

위 문법은 함수를 선언하는 것입니다. 아래처럼 사용할 수 있죠. 

<script type="text/javascript">

function sayHello()
{
   alert("Hello there");
}

</script>

 

 

 

자, 그럼 이렇게 선언해놓은 함수를 어떻게 호출을 할까요?

 

네~ 그렇죠~ 제가 늘 말하는 "아래처럼" 호출하면 되는겁니다~

 

<script type="text/javascript">

sayHello();

</script>

 

 

파라미터

이번에는 파라미터 사용법에 대해서 알아보도록 하겠습니다.

 

자바스크립트의 특징 중 하나가  undefined type이었다는 것을 기억하시나요? 변수를 지정할때 타입을 지정하지를 않죠?  

함수내에 파라미터를 넣을때도 타입을 지정하지 않습니다. 아래처럼 말이죠. 

<script type="text/javascript">

function sayHello(name, age)
{
   alert( name + " is " + age + " years old.");
}

</script>

 

위 소스를 보시면 sayHello()가 파라미터 두개를 받고있네요. name과 age.  

이 함수를 호출할 때에는 파라미터를 두개 넣어주면 되는 겁니다. 

<script type="text/javascript">

sayHello('Zara', 7 );

</script>

 

sayHello 함수에 'Zara' 랑 7을 파라미터로 넘겼네요. Zara의 홑따옴표는 스트링을 의미합니다. Zara라는 스트링을 파라미터로 넘긴다는 말이죠. 

return

자바스크립트의 함수도 결과값을 반환할 수 있습니다. 

 

예제를 한번 볼까요? 

 

<script type="text/javascript">

function concatenate(first, last)
{
   var full;

   full = first + last;
   return  full;
}

</script>

위 소스는 두개의 파라미터를 받아서 두개를 합친 결과를 반환합니다.

 

이제 함수를 호출해서 함수에서 얻은 결과값을 경고창에 띄워보겠습니다. 

<script type="text/javascript">

   var result;
   result = concatenate('Zara', 'Ali');
   alert(result );

</script>

 

 

함수에 대해서 좀 더 자세한 내용을 알고싶으면 아래 링크를 참조하세요 ^____^

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_functions.htm 

 

 

 

오늘은 break문과 continue문, 그리고 label을 어떻게 사용하는지 한번 알아보도록 하겠습니다.

역시나 예제가 우리에겐 최고의 스승이죠? ㅋ

 

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
  if (x == 5){ 
     break;  // while루프에서 빠져나갑니다
  }
  x = x + 1;
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

 

x가 5일 때 break;문이 실행되면서 루프에서 빠져나오게 됩니다. 그래서 결과는 아래와 같이 나오게 되겠죠. 

Entering the loop
2
3
4
5
Exiting the loop!

 

 

 

 continue 문은 그럼 뭘까요? 왠지 break문의 반대같은데 말이죠. continue문은 다음 루프로 넘어가라는 명령입니다. 아직 현재 루프에서 실행되어야 할 문장들이 남아있더라도 말이죠.

아래 예제를 한번 볼까요?

 

 

<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 10)
{
  x = x + 1;
  if (x == 5){ 
     continue;  // x == 5 이면 x를 출력하지않고 다음 루프로 넘어갑니다. 
  }
  document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

 

결과를 아래처럼 나오겠죠. x가 5일때는 continue문 때문에 document.write( x + "<br />"); 문이 실행되지 않습니다. 따라서 2부터 10까지 출력하는데 5만 빼고 출력을 하게되겠죠. 

Entering the loop
2
3
4
6
7
8
9
10
Exiting the loop!

 

 

Labels

JavaScript 1.2 버전부터 label을 beak, continue문과 함께 사용할 수 있게 됐습니다.  

 label 은 간단히 말하면 특정 위치를 지정해주는 역할을 합니다.   

예제를 한번 살펴보도록 합시다. 

Example 1 : break문과 함께 label사용하기

<script type="text/javascript"> <!-- document.write("Entering the loop!<br /> "); outerloop: // 1번 라벨입니다. for (var i = 0; i < 5; i++) // 1번 루프 { document.write("Outerloop: " + i + "<br />"); innerloop: // 2번 라벨입니다. for (var j = 0; j < 5; j++) // 2번 루프 { if (j > 3 ) break ; // 이 문장을 포함하는 가장 가까운 루프를 빠져나옵니다. (여기서는 2번 루프겠죠) if (i == 2) break innerloop; // 이 문장은 innerloop를 빠져나와는 말입니다. ( 2번 루프에서 나오는거죠 ) if (i == 4) break outerloop; // 이 문장은 outerloop를 빠져나옵니다. ( 1번 루프에서 빠져나가는 것이죠 ) document.write("Innerloop: " + j + " <br />"); } } document.write("Exiting the loop!<br /> "); //--> </script>

 

결과는 아래처럼 나오게 됩니다. 

Entering the loop!
Outerloop: 0
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 1
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 2
Outerloop: 3
Innerloop: 0 
Innerloop: 1 
Innerloop: 2 
Innerloop: 3 
Outerloop: 4
Exiting the loop!

 

Example 2 : continue문과 함께 label사용하기

<script type="text/javascript">
<!--
document.write("Entering the loop!<br /> ");
outerloop:   // This is the label name
for (var i = 0; i < 3; i++)
{
   document.write("Outerloop: " + i + "<br />");
   for (var j = 0; j < 5; j++)
   {
      if (j == 3){
         continue outerloop;
      }
      document.write("Innerloop: " + j + "<br />");
   } 
}
document.write("Exiting the loop!<br /> ");
//-->
</script>

 

결과는 아래처럼 나옵니다. 

Entering the loop!
Outerloop: 0
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 1
Innerloop: 0
Innerloop: 1
Innerloop: 2
Outerloop: 2
Innerloop: 0
Innerloop: 1
Innerloop: 2
Exiting the loop!

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_loop_control.htm 

 

 


자~ 오늘은 for 루프에 대해서 알아보도록 하겠습니다.

 

for 루프와 while루프는 100% 바꿔치기가 가능한 녀석들입니다. 어떤 상황에서 어떤 반복문을 사용하느냐는 개발자인 여러분들에게 달려있습니다!!  

우선 문법부터 확인해야겠죠? 어떻게 생긴놈인지 알아야 뭘 써먹더라도 써먹죠 ㅋㅋ 

 

for ( 초기화 ; 조건문 ; 반복실행문 ){
     조건문이 참인 동안 실행되어야 할 문장
}

역시 우리는 예제가 있어야 뭘 알것 같아요 그죠잉?
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++){
  document.write("Current Count : " + count );
  document.write("<br />");
}
document.write("Loop stopped!");
//-->
</script>

 

자 위 코드를 보면 어떤 결과가 나올거라고 예상이 되시나요??  

아래 해답을 보시죠.  

 

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

 

어때요? 쉽죠? 어려우시다구요? 그럼 설명을 좀 해드릴게요.

 

for ( count = 0 ; count < 10 ; count++ ) : for루프를 시작하는 부분입니다. 변수 count를 0으로 초기화 합니다. count변수의 값이 10보다 작을 동안 실행하라는 조건을 줬습니다. 그리고나서 매 루프가 끝나면 count를 1씩 증가시키도록 합니다.

여기서 세미콜론 ( ; ) 잊어먹지 않도록 조심하세요.

문법이 어렵다면 연습만이 당신을 살릴 수 있으니 연습하세요. ㅋㅋ

 

 

자, 또 다른 for 루프가 있습니다. 객체를 이용하는 것인데요~ 형식을 한번 볼까요?

 

 

for (변수명 in 객체){
  실행할 문장
}

 

 

 

아래 예제는 웹브라우저의 Navigator객체에 있는 속성을 출력하는 기능을 for루프로 구현해놓은 것입니다. 

<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
  document.write(aProperty);
  document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>

 

결과는 아래처럼 나오겠죠? 아닌가요? 맞나? 확인해보세요~~ ^___^ 

Navigator Object Properties
appCodeName
appName
appMinorVersion
cpuClass
platform
plugins
opsProfile
userProfile
systemLanguage
userLanguage
appVersion
userAgent
onLine
cookieEnabled
mimeTypes
Exiting from the loop! 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_for_loop.htm 

 

 


이번 포스팅에서는 자바스크립트의 while 루프문에 대해서 알아보도록 하겠습니다.

 

우선 문법부터 확인해볼까요??

 

 

while (조건문){
   조건문이 참인동안 실행해야할 문장
}

 

이제 예제를 한번 볼까요??
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
while (count < 10){
  document.write("Current Count : " + count + "<br />");
  count++;
}
document.write("Loop stopped!");
//-->
</script>

 

결과가 어떻게 나올것 같나요??

아래처럼 나와야겠죠??

 

Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped! 

 

 

 

 

자 while문과 비슷한 do-while문을 아시나요? do-while문은 일단 먼저 한번 실행시킨 다음에 while문을 타는겁니다.

역시 말보다는 실습이죠? 

 

문법부터 확인해볼까요??
do{
  최소 한번은 실행되어야 하는 문장
} while (조건문);

그럼 이제 예제를 한번 봅시다.
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br />");
do{
  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>

 

결과가 예상이 되나요?

아래처럼 결과를 예상하셨다면 당은은 자바스크립트의 중수가 되신겁니다~ 축하드려용~~ㅋㅋ 

Starting Loop
Current Count : 0
Loop stopped! 

 

간단하죠??

별거 없습니다 ㅎㅎ

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_while_loop.htm

 

 


JavaScript 1.2부터 switch문을 사용할 수 있습니다. switch문이 뭐냐? 문법부터 일단 보시죠. 

 

switch 문은 크게 switch절과 case절 그리고 default절이 있습니다. switch절에는 변수가 들어가는데 if문에서처럼 참, 거짓을 반환하는조건이 들어가는 것이 아닙니다. 이 변수는 어떤 값을 가지고 있겠죠? 그 값들을 case 절에 써주는 겁니다. case절은 여러개가 올 수 있는데 만약 모든 case절에서 매치되는 값을 못찾으면 default절의 문장을 실행하고 switch문은 종료됩니다.

switch (변수)
{
  case 값1: statement(s)
                    break;
  case 값2: statement(s)
                    break;
   ...
  case 값n: statement(s)
                    break;
  default: statement(s)
}

break 문은 특정 case가 끝났다고 알려주는 문장입니다. 만약 이 break문이 없으면 밑에있는 case안에 있는 문장들도 실행을 하게 됩니다.

 

 

그럼 예제를 한번 보실까요??

 

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
            break;
  case 'B': document.write("Pretty good<br />");
            break;
  case 'C': document.write("Passed<br />");
            break;
  case 'D': document.write("Not so good<br />");
            break;
  case 'F': document.write("Failed<br />");
            break;
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

 

결과가 아래처럼 나오면 맞는건가요? 여러분이 직접 한번 해보시고 말씀해주세요 ^___^ 

Entering switch block
Good job
Exiting switch block

 

 

 

이번에는 break문을 생략했을 때 어떻게 실행되는지 한번 알아보죠. 

 

<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
  case 'A': document.write("Good job<br />");
  case 'B': document.write("Pretty good<br />");
  case 'C': document.write("Passed<br />");
  case 'D': document.write("Not so good<br />");
  case 'F': document.write("Failed<br />");
  default:  document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>

 

결과는 아래처럼 나옵니다. 

Entering switch block
Good job
Pretty good
Passed
Not so good
Failed
Unknown grade
Exiting switch block

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_switch_case.htm 

 


오늘은 자바스크립트의 if문에 대해서 알아보도록 하겠습니다.

다른 프로그래밍 언어와 마찬가지로 자바도 if문, if-else문, 그리고 if-else if-..-..-else문을 지원합니다.

하나씩 차례대로 배워보죠. 

if 문

if문의 문법은 아래와 같습니다.

 

 

if (조건){
   조건이 참일때 실행되어야 할 문장
}

조건의 결과가 참인 경우에만 안쪽에 있는 문장을 실행시킵니다.

 

예제를 한번 보실까요??

<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}
//-->
</script>

 

위 코드는 아래와 같은 결과를 보여주겠죠?? 

Qualifies for driving

 

다음은 if-else문을 한번 보겠습니다. 

if...else 문

if문에서 else만 추가된 거죠. 문법은 아래와 같습니다.

 

 

if (조건){
   조건이 참이면 실행될 문장
}else{
   조건이 거짓이면 실행될 문장
}

조건이 참이면 if내의 문장을 실행하고 거짓이면 else내의 문장을 실행합니다. 

 

 

예제를 보도록 하겠습니다. 

<script type="text/javascript">
<!--
var age = 15;
if( age > 18 ){
   document.write("<b>Qualifies for driving</b>");
}else{
   document.write("<b>Does not qualify for driving</b>");
}
//-->
</script>

 

아래처럼 결과가 나오는게 맞나요?? 맞습니다~ 

Does not qualify for driving

 

if...else if... 문

이것도 어렵지 않습니다. 그저 else를 여러개 붙여 놓은 거라고 보시면 됩니다. 문법부터 한번 보시죠. 

 

 

if (조건 1){
   조건 1이 참이면 실행되야 할 문장 - A
}else if (조건 2){
   조건 1이 거짓이고 2가 참이면 실행되야 할 문장 - B
}else if (조건 3){
   조건 1, 2가 모두 거짓이고 3이 참이면 실행되야 할 문장 - C
}else{
   조건 1, 2, 3이 모두 거짓이면 실행되야 할 문장 - D
}

위 문법을 말로 풀어쓰면 이렇게 되는겁니다.  

 

만약 조건1이 참이면 A를 진행하고 B, C, D는 실행하지 마세요.

만약 조건1이 거짓이고 조건2가 참이면 B만 실행하세요.

만약 조건 1과 2가 모두 거짓이고 조건3이 참이라면 C만 실행하세요.

만약 조건1, 2, 3 모두가 거짓이면 D를 실행하면 됩니다. 

 

예제를 한번 보시죠.
<script type="text/javascript">
<!--
var book = "maths";
if( book == "history" ){
   document.write("<b>History Book</b>");
}else if( book == "maths" ){
   document.write("<b>Maths Book</b>");
}else if( book == "economics" ){
   document.write("<b>Economics Book</b>");
}else{
  document.write("<b>Unknown Book</b>");
}
//-->
</script>

 

결과가 아래처럼 나오는게 맞는건지 여러분이 판단해 보세요. 

Maths Book

 

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_ifelse.htm