자바스크립트강좌 (15)

💻 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

 

 

 

 

 

자바스크립트 이미지 맵

이미지 맵이란 뭘까요?

아래 예제는 이미지의 특정 영역에 마우스를 올려놓으면 특정 기능이 실행이 되고 클릭을 하면 특정 URL로 이동시켜주도록 되어있습니다.

소스를 보시면 <map>과 <area>태그가 사용된 것이 보이는군요.

<area>에서는 영역을 지정해주고 영역내에서 일어나는 이벤트에 대해서 어떤 기능을 실행할지 지정해주고 있습니다.

그리고 이 태그들을 <map>태그가 감싸고 있는 형태군요.

실행해보시면 이해가 잘 될겁니다.

<area>태그에서 coords는 영역을 나타내는 포지션을 말합니다.

poly에서는 연속되는 두개의 숫자가 한 점의 위치를 지정해줍니다.

아래 예제에서는 10개의 숫자가 있으니 총 5개의 점으로 표현되겠군요.

rect에서는 사각형을 그리기위한 네개의 숫자가 필요합니다.

가장 왼쪽 아래의 점의 좌표와 그 점의 대각선에 위치한 점의 좌표겠죠.

circle에서는 원을 나타내기위한 세개의 숫자가 있네요.

중심점 좌표(숫자 2개)와 반지름의 값인 것 같네요.

좌표를 하드코딩하지 않는 방법을 생각해서 구현하면 쓸만할 것도 같네요.

 

<html>
<head>
<title>Using JavaScript Image Map</title>
<script type="text/javascript">
<!--
function showTutorial(name){
  document.myform.stage.value = name
}
//-->
</script>
</head>
<body>
<form name="myform">
   <input type="text" name="stage" size="20" />
</form>
<!-- Create  Mappings -->
<img src="/images/usemap.gif" alt="HTML Map" 
        border="0" usemap="#tutorials"/>

<map name="tutorials">
   <area shape="poly" 
            coords="74,0,113,29,98,72,52,72,38,27"
            href="/perl/index.htm" alt="Perl Tutorial"
            target="_self" 
            onMouseOver="showTutorial('perl')" 
            onMouseOut="showTutorial('')"/>

   <area shape="rect" 
            coords="22,83,126,125"
            href="/html/index.htm" alt="HTML Tutorial" 
            target="_self" 
            onMouseOver="showTutorial('html')" 
            onMouseOut="showTutorial('')"/>

   <area shape="circle" 
            coords="73,168,32"
            href="/php/index.htm" alt="PHP Tutorial"
         target="_self" 
            onMouseOver="showTutorial('php')" 
            onMouseOut="showTutorial('')"/>
</map>
</body>
</html>

 

실제 동작하는 모습은 tutorialspoint 사이트에서 확인 가능합니다.

 

 

 

Reference : http://www.tutorialspoint.com/javascript/javascript_image_map.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

 

 


JavaScript 데이타 타입

JavaScript에는 세가지 primitive 데이타 타입이 존재합니다. 숫자, 스트링, 그리고 참, 거짓을 나타내는 boolean이 바로 그 데이타 타입입니다. 자바스크립트에는 또한 nullundefined 라는 데이타 타입이 있습니다. 좀 특수한 녀석들이죠. 

그리고 마지막으로, 자바스크립트도 자바와 마찬가지로 객체타입을 지원합니다.  

JavaScript에서 숫자는 소수점 형태의  값으로 표현됩니다.  IEEE 754 표준에 정의된 64-bit 소수점 형태로 말이죠.

JavaScript 변수

자바스크립트에서 변수를 선언할 때는 var키워드를 사용합니다.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

 

여러개의 변수를 선언할 때 꼭 var를 앞에 붙여야 하나요? 아닙니다. 아래처럼 한줄에 var키워드를 한번만 써서 변수 두개를 선언할 수도 있습니다. 

<script type="text/javascript">
<!--
var money, name;
//-->
</script>

이렇게 선언된 변수에 값을 넣는것을 변수 초기화라고 합니다. 변수 초기화는 변수를 선언할 때 할 수도 있지만 나중에 할 수도 있습니다.아래 예제를 한번 볼까요?

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

위 예제에서 ​name이라는 변수는 변수 선언과 동시에 초기화를 해주었습니다. 그런데 money변수는 선언을 하고 난 뒤에 나중에 변수를 초기화했죠. 

여타의 프로그래밍 언어와는 다르게 자바스크립트는 변수의 타입을 지정해주지 않습니다. 변수에 들어갈 값이 스트링인지 숫자인지 관계가 없다는 말이죠. 이건 자바스크립트가 알아서 자동으로 케어해주니 신경쓰지 않으셔도 됩니다.  

JavaScript 변수의 범위

변수에는 크게 전역 변수와 로컬 변수가 있습니다. 전역 변수는 global 변수로 어디서나 접근이 가능한 변수이고 로컬변수는 그 변수가 정의된 함수 내에서만 사용될 수 있는 변수를 말합니다.

동일한 이름의 변수를 선언하게 된다면 로컬에서는 전역변수보다 로컬변수가 우선순위가 높기 때문에 로컬변수를 사용하게 됩니다.  

아래 예제를 한번 보시죠. 

<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
   var myVar = "local";  // Declare a local variable
   document.write(myVar);
}
//-->
</script>

 

myVar라는 이름을 갖는 변수가 두 번 선언되었습니다. 하나는 전역변수이고 하나는 로컬 변수죠.

위 스크립트의 실행 결과가 어떻게 나와야 맞는 걸까요??

추측해보시고 결과는 스크립트를 실행시켜서 확인해보세요 ^__^

 

JavaScript 변수명 규칙

 

자바스크립트에서 변수이름을 정할때는 아래와 같은 규칙을 지키셔야 합니다.

  • JavaScript 예약어 사용 금지

  • 숫자로 시작할 수 없다. 문자나 밑줄로 시작해야 한다.  

  • 대소문자를 구분한다.

 

JavaScript 예약어 목록

abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with

 

 

 

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

 

 


안녕하세요~~ 케이치입니다~


오늘은 자바스크립트를 삽입하는 방법


자바스크립트 코드는 헤드, 바디 태그 안에 들어갈 수도 있고 두 태그 모두에 들어갈 수도 있고, 외부파일로 정의해서 include할 수도 있습니다. 각각 어떻게 하는지 한번 알아보죠. 


 <head> 태그 내의 JavaScript

사용자가 발생시키는 특정 이벤트에 대해서 자바스크립트가 동작을 해야한다면 헤드태그 안쪽에 코드를 삽입합니다.

 

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

 

 

 <body> 태그 내의 JavaScript

웹페이지가 로드될 때 자바스크립트 코드에 의해서 어떤 내용물이 화면에 출력되어야 한다면 바디 태그 안에 스크립트를 넣어주세요. 이 경우에는 자바스크립트 코드로 정의된 함수는 가질 수 없습니다.

 

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

 

결과는 아래처럼 보이겠죠?

 

Hello World
This is web page body

 

 

<body> 와 <head>에 동시에 쓰이는 JavaScript

 

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

 


외부 파일로 정의된 JavaScript

JavaScript를 좀더 확장해서 쓰려면 외부파일로 정의해서 쓰는 방법이 있습니다. 기능별로 파일을 분리해서 정리하면 관리하기가 편해지겠죠. 이건 뭐 어떻게 관리하느냐에 따라 달렸지만요 ㅋ 여러 페이지에서 동일한 스크립트를 사용해야 한다면 분리해서 사용하시는 것이 편리할겁니다.

자바스크립트 코드를 외부파일로 저장하려면 .js확장자를 사용합니다. 그리고 이 파일을 include하는 방법은 src속성을 이용해서 파일경로를 지정해주면 됩니다. 


<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

 

 

filename.js 

function sayHello() {
   alert("Hello World")
}

 

 

한번씩 다 해보시고 안된다 하시는게 있으시면 댓글로 질문 남겨주세요~ ^-^


이상 케이치였습니다~


즐프하세요~~ ^-^

 

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