HTML/java script2012. 10. 12. 20:51

  

 

<< 실행화면 >> -> 옮기려는 사이트를 선택하고 선택을 하면 해당 사이트로 이동.

 

<참고>

<a href="http://developia.net" target="test">developia</a><br/> 와 같이 target을 설정해놓으면 새로운 웹브라우저를 키고 이동을 한다.

 

// test의 이름은 변경 가능하다.

// test이름을 주지 않으면 새로운창 없이 그 웹페이지에서 창이 뜬다.

 

 

 

<< 소스 >>

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Selected를 이용한 select 박스 예제.</title>
</head>
<body>

<script type="text/javascript">
var gosite = function(){
 var f = document.dev;
  
 if(f.site.options[0].selected){
  alert('이동할 사이트를 선택하세요');
  f.site.focus()
  return;
 }else{
  for(var i = 0; i<f.site.options.length;i++){
   if(f.site.options[i].selected){
    alert(f.site.options[i].text + " : " + f.site.options.selectedIndex);
    
    // 자기자신을 호출한 사이트로 이동. location.href는 인터넷 URL 경로 설정용도.
    location.href=f.site.options[i].value;
   } 
  }
 }
}
</script>

<form name="dev">
<!--  자기자신을 체크하는 self.location 태그. -->
 <select name="site">
<!--   onchange="javascript:self.location -->
<!--   =document.dev.site.options[document.dev.site.options.selectedIndex].value"> -->
  
  <option selected> --이동할 사이트 선택 </option>
  <option value="http://daum.net">daum</option>
  <option value="http://naver.com">naver</option>
  <option value="http://developia.net">devlopia</option>
 </select>
 <input type="button" value="선택" onclick="javascript:gosite();"/>
</form>
</body>
</html>

 

 

 

 

* 새로운 창을 띄울 때 예제.

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<!--  target을 설정하면 새로운 윈도우가 열림. -->
<a href="http://developia.net" target="test">developia</a><br/>


<!--  #의 의미가 뭐지. -->
<a href = "#" onclick="javascript:window.open('http://developia.net',
  'newWindow','width=500px, height=200px');">developia</a><br/>

</body>
</html>

 

 

 

 

 

'HTML > java script' 카테고리의 다른 글

윈도우객체  (0) 2012.10.12
HTML에 자바스크립트 삽입  (0) 2012.10.04
로케이션객체  (0) 2012.10.04
자바스크립트(JavaScript) 기본  (0) 2012.02.23
Posted by wrnly
HTML/java script2012. 10. 12. 20:37

<script>
    // window 객체 : 자바스크립 최상위 객체 : C#의 object 클래스
    // window.alert() : 경고 대화상자
    // window.confirm() : 확인 대화상자
    // window.prompt() : 입력 대화상자 : 거의 안씀
    window.status = "상태바에 문자열 출력"; // 속성
    // window.open() : 새 창(window) 띄우기
    // window.close() : 현재 창 닫기
    // window.setTimeout(code, delay) : 시간차/타이머
</script>
<script>
    function CheckDelete() {
        //확인 버튼 클릭하면, true 취소 버튼 : false
        var flag = window.confirm("정말로삭제?");
        if (flag) {
            alert("삭제진행");
            return true;
        }
        else {
            alert("멈춤");
            return true;
        }
    }
</Script>   
<script>
    function OpenDNK() {
        window.open("http://www.naver.com/", "naver", "옵션???");
    }
</script>
<script>
    function Go() {
        // 3초 후에 앞에 명령어 실행
        window.setTimeout("alert('퐁~');", 3000);
    }
</script>
<!-- 경고 대화상자 -->
<input type="button" value="클릭" onclick="window.alert('경고');" />
<input type="button" value="삭제" onclick="CheckDelete();" />
<input type="button" value="입력" onclick="window.prompt('나이?', '여기');" />
<input type="text" value="닷넷코리아" onclick="OpenDNK();" />
<input type="button" value="닫기" onclick="window.close();" />
<input type="button" value="열기" onclick="Go();" />

Posted by wrnly
HTML/java script2012. 10. 4. 22:23

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>HTML에 자바스크립트 삽입</title>
    <style type="text/css">
        body
        {
            color: blue;
        }
    </style>

    <script language="javascript" type="text/javascript">
        // 도큐멘트 객체(개체)의 Write 메서드(Method, 출력)로 화면에 출력
        document.write("안녕하세요.<br/>")
        document.write("반갑습니다.<br/>")
        // 윈도우 객체의 alert() 함수 호출로 경고대화상자(메시지박스) 출력
        window.alert("또 만나요.\n낼 봐요.");
    </script>

</head>
<body>
</body>
</html>

'HTML > java script' 카테고리의 다른 글

[Javascript] location.href와 target 이용한 URL 링크 걸기  (0) 2012.10.12
윈도우객체  (0) 2012.10.12
로케이션객체  (0) 2012.10.04
자바스크립트(JavaScript) 기본  (0) 2012.02.23
Posted by wrnly
HTML/java script2012. 10. 4. 21:36

<script>
    function GoNaver() {
        location.href = "http://www.naver.com/";
    }
</script>
<input type="button" value="닷넷코리아로 이동" onclick="location.href='http://www.dotnetkorea.com/';" />
<table border="1" onmouseover="GoNaver();">
<tr><td>마우스를 올려보세요...</td></tr>
</table>
<a href="#" onclick="location.reload();">현재 페이지 새로고침</a>
<a href="javascript:location.reload();">현재 페이지 새로고침</a>

'HTML > java script' 카테고리의 다른 글

[Javascript] location.href와 target 이용한 URL 링크 걸기  (0) 2012.10.12
윈도우객체  (0) 2012.10.12
HTML에 자바스크립트 삽입  (0) 2012.10.04
자바스크립트(JavaScript) 기본  (0) 2012.02.23
Posted by wrnly
HTML/java script2012. 2. 23. 15:22

자바스크립트(JavaScript) 기본

html태그로는 만족시켜주지 못한것들을 css로 메꿀수있지만 어디까지나 정적인 부분이었다면
자바스크립트를 이용하여 보다 다양한 변화를 줄수가 있다.

JavaScript는 HTML문서속에 포함되어서 전송되어 진다. 즉, 브라우져가 특정한 HTML을 요청하게 되면, 웹서버가 이를 브라우져에게 전송하게 된다. 브라우져는 HTML부분은 화면에 출력하고, JavaScript부분은 실행하게 되는 것이다.

 JavaScript는 HTML문서내에 포함되어서, 사용자의 행위(event)에 반응하게 된다. 예를 들면, 마우스를 클릭한다거나, HTML의 Form Tag항목에 값을 집어넣거나, 브라우져의 행위 중 일부를 통제하게 된다. 

 그러나, 역시 가장 중요한 사용처는 사용자의 입력을 확인하는 작업을 한다는 것이다. 즉, 주민번호를 입력 받아야하는 항목이 하나있다고 할 때, 그것이 바르게 입력되었는지 확인할 수 있는 것이다. 

사용자의 입력을 확인 이것은 대단히 중요한 일이다. 왜냐하면, JavaScript가 없는 경우를 생각해보면 간단하다. 그럴 경우 사용자가 뭘입력하든 일단 서버로 보내서 서버가 확인을 하고 틀리는 경우 에러 메세지를 다시 보내줘야 한다. 이렇게 되면, 사용자 입장에서는 확인하는 동안 기다려야하기 때문에 짜증이고, 네트웍에 부하를 주며, 서버는 쓸데없는 작업에 자원(resource)를 낭비하는 결과를 초래하게 되는 것이다. 즉, 간단히 확인할 수 있는 것들은 JavaScript를 이용해서 일단 걸러주고 서버로 보낸다는 것이다.


--- JavaScript

기본문법

javascript 문법 직접 입력(<head> 와 </head>사이에 위치함)

<script language="javascript">
//<!--
 스크립트 문법
//-->  <!-- -->를 사용하는 이유는 옛날에 script를 지원하지않는 브라우져에는 감추기 위해서인데 현재로썬 필요없다. 
</ script>

========================================================
<html>
<head>
 <title>소스 1-1 </title>
 <script language="javascript">
 
  document.write("<h3>예제 1: 이것이 기본 태그이다.</h3>")
 </script>
 <script language="javascript">
  document.write("<h3>language에서 스크립트 언어 종류를\
  결정한다.</h3>") //역 슬레쉬 \은 다음문장을 연결한다.
                        document.write("<h3>language에서 스크립트 언어 종류를<br>\
  결정한다.</h3>")//<br>줄을 바꾼다.
           </script>
         
</head>
<body>

</body>
</html>


* Script file 호출
   <script language="javascript" src="script.js">
   script file은 자바스크립트로만 작성되어 있어야 한다.
   확장자명은 ".js"

* 메모리상에 객체에 있는 속성 값을 사용할려면 쌍따움표 사용하면 안된다.

* 문자열이나 객체,속성값을 연결하기위해서는 +나 ,연산자를 이용한다.

* 변수의 사용-  var 변수명

* 비주얼 스크립트는  <script language="vbscript"> 라고 명기 해야한다.
   (explorer 전용)

* 스크립트는 라인 단위로 수행한다
   한개의 line에서 2개의 문장을 수행할시에는 문장뒤에다 ; 을 사용한다.

* 두개의 단어가 결합된 것은 앞의 단어가 소문자, 뒤에 단어가 대문자.

* window.alert(" ")  - 확인이란 창을 만든다.
   window.alert 창 안에서 줄바꾸기는  \n을 사용한다.
  

=====================================================================

자바 스크립트의 기본문법 1

*variables, operators
1. 변수의 선언 및 규칙
2. 연산자 (산술, 관계, 논리, 조건)

*statement
1. 제어문(if, switch문)
2. 반복문(for문, while문, do while문)

*javascript function
1. 함수의 기본 형식
2. window객체의 유용한 method
3. 내장함수
-------------------------------

변수란?
메모리에 저장되는 기억장소의 이름

변수의 선언
var total(var 생략 가능)
var aNum, bNum
var count=10

temp=10 변수type가 정수형으로 설정된다
temp="하하하"  문자형으로 설정된다.
- 변수는 하나의 기억장소안에 하나의 데이터형태만
   들어간다.

null (아무값도 대입없이 사용할때)
undefined(초기화 되어 있지 않은 상태)

NaN(Not a Number)- 값이 숫자가 아님

전역변수(global variable)
-함수 밖에 선언된 모든 변수
  함수안에 var없이 선언된 변수
  함수가 끝나도 메모리에 남아 있음

지역변수(local variable)
-함수안에 var를 사용하여 선언된 변수
  함수가 끝나고 나면 자동으로 사라짐


<html>

<head>
<script language="javascript">
var hello = "(함수 밖)전역변수\'hello\'"
function thisfunction()
{
       var hello="(함수 안)지역변수\'bye\'";
       global="(함수 안)전역변수\'global\'";
       var local="(함수 안)지역변수\'local\'";
       window.alert(hello);
       window.alert(global);
       window.alert(local);
}
</script>     
</head>

<body>
<input type="button" value="실행"
 onClick="thisfunction();alert(hello)">

</body>

</html>

논리 연산자
 
 ||(or)   -A와 B중 하나만참
 &&(and)  -A와 B가 둘다 참
 !(not)  -참 거짓  반대로
 ^(xor)  -A&&(!B) || (!A)&&B


조건 연산자

A=(조건) ? X : Y


숫자와 문자의연산 

+ String "123" String "abc" Integer 123 Float 1.23 Boolean true Boolean false null
String "123" 123123 123abc 123123 1231.23 123true 123false 123null
String "abc" abc123 abcabc abc123 abc1.23 abctrue abcfalse abcnull
Integer 123 123123 123abc 246 124.23 124 123 123
Float 1.23 1.23123 1.23abc 124.23 2.46 2.23 1.23 1.23
Boolean true true123 trueabc 124 2.23 2 1 1
Boolean false false123 falseabc 123 1.23 1 0 0
null null123 nullabc 123 1.23 1 0 0
  • 숫자와 숫자사이의 덧셈은 진짜 더하게 된다.
  • 숫자와 문자열을 더하게 되면 문자열 합치기가 일어난다.
  • 숫자와 연산을 하는 true, false, null은 각각 1, 0, 0 값을 가지게 된다.
  • 문자열이 아니면 기본적으로 숫자로 간주한다.
  • 문자열과 연산을 하는 true, false, null은 각각 "true", "false", "null"로 변경되어 문자열 합치기가 일어난다.



증감 연산자

++ ++a  1씩 먼저 증가
 a++ 1씩 나중 증가

-- --b 1씩 먼저 감소
 b-- 1씩 나중 감소
-----------------------------------------

조건문
if( condition1 ) {
   // .... 조건1이 참일 때, 수행되는 부분
}else if( condition2 ){
   // .... 조건2가 참일 때, 수행되는 부분
}else if( condition3 ){
   // .... 조건3이 참일 때, 수행되는 부분
}else{
   // 앞의 모든 조건에 해당하지 않았을 때 수행되는 부분
}



switch( value ){
    case value1: // 1 Link
       .................................
       break;
    case value2: // 2 Link
       .................................
       break;
    default: // 3 Link1
       .................................
       break;
}


반복문
for(i=0;i < 10;i++){
        document.write(i);
}

for(var j in obj){    # obj가 가지고있는 모든속성을 answer에 담는다.
     answer += "" + i + ":" + obj[i];
}

var num = 1;
while (num <= 10){
     document.wirteln(num);
     num++:
}

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


객체란 간단히 속성과 함수를 가지고 있는 모듈(Module)단위를 말한다. 즉, 특정한 기능을 하도록 내부에 변수와 외부와의 연동을 위해서 함수를 제공하는 것이다. 

쉽게 말하면, 우리가 일상생활에서 접하는 것들은 절차(Process)위주로 해석하기보다는 객체로 바라보는 것이 편하다. 그럼 객체가 뭔가? 쉽게 말하면, 마우스, 자동차, 개, 책, 모니터, 커피, ..... 이러한 것들이 다 객체이다. 

즉, 우리가 현실세계에서 바라보는 모습을 그대로 프로그램에도 적용하면 간단하다는 것이다. 몇 번 루프를 돌고, 이럴 때는 이렇게 저럴 때는 저렇게 해야 한다가 아니라, 사람이라는 객체가 있으면, 그 객체 자신이 고유한 속성과 일을 하는 동작, 즉 프로세스를 담고 있기 때문에 어떤 일을 진행하고 싶으면 그 사람에게 명령을 내리면 된다.(군대처럼!)

그 나머지 실제적인 행위는 그 객체 즉, 그 사람이라는 객체가 알아서 하는 것이다. 그런 사람, 책, 컴퓨터 같은 것들을 전부 객체로 구성하여 놓는 것이다.

예를들어, 자동차라는 객체가 있다면, 소나타라는 특징을 가지는 자동차를 만들려면, 자동차라는 객체를 가지고 속성 값만 바꿔서 변수처럼 선언하게 되면 바로 소나타라는 자동차가 되는 것이다. 그럼, 바로 자동차가 간다, 선다와 같은 행위(쉽게 말하면 함수)를 불러주면 간단히 해결되는 것이다.

모든 객체는 속성(Attribute)과 함수(Function, Behavior)를 가지고 있다. 그래서 그 객체가 가지고 있는 속성이나 함수를 부르거나 값을 가져오려면(Access), 
객체이름.객체속성 
객체이름.함수() 
 

함수의 정의

function 함수이름(매개변수 1,2...)
{
 함수 문장
return 값 

}

*매개 변수(parameter) : 입력되는 것
  리턴 값(return value)  : 함수 계산결과 나오는 값

함수클래스
<script language="javascript">
 
function me(name, age){
 
this.name = name;
 
this.age = age;
 
this.print = function print(){
 
alert(this.name);
 
alert(this.age);
 
}
 
}
 
var i = new me("cdral", 20);
 i.print();
</script> 
this는 this라는 문자가 들어가 있는 가장 바깥쪽의 괄호의 주인을 가리킨다. 즉, this는 me라는 함수 자신이 되는 것이다. 정확히 말하면 생성되는 객체 자체를 가리킨다. new라는 연산자에 의해서 생성되는 객체를 this가 지칭한다.


-- Window 객체의 유용메소드 --

1. alert method
: 경고나 문제부분을 사용자에게 알리는 함수
 window.alert("문자열")
 
<html>

<head>
<script language="javascript">
<!--
    window.alert("실전자바스크립트\n\n강력해진 내홈피")
//-->
</script>
</head>

<body>
</body>

</html>

2. prompt method
: 사용자의 입력을 받기 위한 대화상자
 prompt( 문자열, 초기값 )

<html>

<head>
<script language="javascript">
<!--
    var qs
    qs=prompt("좋아하는 언어를 선택하세요. 1.자바 2.비주얼베이직 3.자바스크립트"," ")
    if(qs==1)
       document.write("자바를 좋아하시는 군요")
    else if(qs==2)
       document.write("비주얼베이직을 좋아하시는 군요")
    else if(qs==3)
       document.write("jsp를 좋아하시는 군요")
    else
       document.write("잘못선택 하셨네요")
     
//-->
</script>
</head>
<body>
</body>

</html>

3. confirm method
: 사용자가 확인이나 취소를 선택하는 함수
 confirm( 문자열)


<html>

<head>
<!--
     cancle=confirm("삭제하시겠습니까?")
     if(cancle==true)
        document.write("삭제되었습니다.")
     else
        document.write("취소되었습니다.")
//-->
</head>

<body>
</body>

</html>

-- 자바스크립트 내장함수 --

* eval(문자 수식)
 : 문자열로 된 수식의 계산결과를 return하는 함수
 
   [예] eval( "2+3" )
                 <-- 5

* parseFloat(문자 수식)
 : 문자열을 실수로 return하는 내장함수

   [예] parseFloat( "15.5" )

* parseInt(문자 수식)
: 입력되는 값을 정수로 return 하거나 특정 진수로 return

   [예] parseInt("17") + 4   ---> 21
           parseInt( "17",8 )    8진수 17는 얼마 ---> 15
           parseInt("15",10)    10진수 15는 얼마 ---> 15
           parseInt("15",16)    16진수 15는 얼마 ---> 21

<html>

<head>
<script language="javascript">
<!--
    var word, num
    word="3*5"//문자
    num=3*5
    document.write("word="+word+"<br>")
    document.write("eval(word)="+eval(word)+"<br>")
    document.write("num="+num+"<br>")
    eval("var re"+"sult=15")
    document.write("result="+result+"<br>")
//-->
</script>
</head>

<body>
</body>

</html>

-----> word=3*5
 eval(word)=15
 num=15
 result=15


 
<html>

<head>
<script language="javascript">
<!--
var num1, num2, num3
num1="15.5"+15.3  //문자열
num2=parseFloat("15.5")+15.3     //실수
num3=parseFloat("'15.5'+15.3")  //NaN

document.write("1)"+num1+"<p>")
document.write("2)"+num2+"<p>")
document.write("3)"+num3+"<p>")
//-->
</script>
</head>

</html>


-----> 1)15.515.3
 
 2)30.8

 3)NaN

* escape()
: 특수문자를 %문자열로 return하는 함수

   [예] escape("$")  --->%24
              #암호처리시 사용
* unescape()
: %문자열을 입력하면 특수문자 return하는 함수

   [예] unescape( "%24" )  ---> $


 
<html>

<head>
<script language="javascript">
<!--
var num1, num2
num1="$"
num2="&"
num3="!"
num4="?"
num5="%"
document.write("1)"+escape(num1)+"="+unescape("%24")+"<p>")
document.write("2)"+escape(num2)+"="+unescape("%26")+"<p>")
document.write("3)"+escape(num3)+"="+unescape("%21")+"<p>")
document.write("4)"+escape(num4)+"="+unescape("%3F")+"<p>")
document.write("5)"+escape(num5)+"="+unescape("%25")+"<p>")
//-->
</script>
</head>
</html>

------->1)%24=$
  
 2)%26=&

 3)%21=!

 4)%3F=?

 5)%25=%


* isNaN()
: 입력된 값이 숫자인지 문자인지 판별해주는 함수
  숫자일경우 false, 숫자가 아닐경우 true
   [예] isNaN( "이건숫자냐?" )  ---> true return

   
<html>

<head>
<script language="javascript">
<!--
var num1, num2
num1="숫자가 아님"
num2=12345

document.write("1)"+isNaN(num1)+"<p>")
document.write("2)"+isNaN(num2)+"<p>")
//-->
</script>
</head>
</html>


-- 기본 문법 --

 -숫자 이외의 문자가 찍히면 화면에 보이지 않기

<html>

<head>
<script language="javascript">
<!--
function num()
{
   if((event.keyCode<48)||(event.keyCode>57))
   {
     event.returnValue=false;
   }
}

//-->
</script>
</head>
<body>
<form>
전화번호: <input type=text size=10 name="tel" OnKeypress="num();">
</form>
</body>
</html>


- 데이터 타입을 알아내는 방법
   ---> typeof 변수명


--  내장객체  --

Array 객체(일괄 처리)
 :여러 Data를 하나의 이름으로 저장하고 다루기 위해 사용 하는 객체

String 객체
 :글자의 모양을 지정하거나 문자열을 처리하기 위해 사용하는 객체

Date 객체
 :날짜와 시간을  표시하거나 설정

Event 객체
 :로컬컴퓨터에서 발생하는 이벤트에 관한 속성 정보 알려는 객체

Math 객체
 :수학 계산을 위해 사용되는 객체

Function 객체
 :함수를 만들때 사용하는 객체

Screen 객체
 :Local 컴퓨터의 화면의 해상도나 색상에 관한 정보를 알기위한 객체

Number 객체
 :문자로된 숫자 단어를 실제 숫자로 바꾸어 주는 객체

Boolean 객체
 :bool형식의 값을 가지는 객체를 만들어주는 객체



1> 배열을 만들어 주는 Array객체
    형식]
  배열객체명 =new Array(); 
 배열객체명.method

     예>
   myFile =new Array('서진숙','대한민국',7)
 myFile.length
 document.write(myFile[2]);


 *property
  -배열객체명.length
    :배열에 있는 요소의 개수를 반환
 
  Method---------------------------------------
  concat()  -두 배열을 연결시켜 하나의 배열로 반환
  join()    -배열에 있는 모든값 합쳐 하나의 문자열 반환
  reverse() -배열의 내용을 역순으로 반환
  slice()    -배열의 특정 부분을 반환
  sort()    -정렬된 배열 반환

  
<html>

<head>
<script language="javascript">
<!--
a=new Array("중앙","사이버","교육",2001)
b=a.length
c=a.join("+")
d=a.slice(1,3)  // [1]<= 값출력 >[3]
a2=new Array("21C","실전자바스크립트")
e=a.concat(a2) //a 와 a2를 연결해서 출력
f=a.reverse()
a3=new Array(30,10,50,40,20)
g=a3.sort() //작은수 --> 큰수로 정렬
document.write("length="+b+"<br>")
document.write("join("+")="+c+"<br>")
document.write("slice(1,3)="+d+"<br>")
document.write("concat="+e+"<br>")
document.write("reverse="+f+"<br>")
document.write("sort="+g+"<br>")
//-->
</script>
</head>

</html>

--------------
var arr=new Array("하이",100,"cdral","java","XX");
document.write("<h2>배열내용</h2>");
for(i=0;i<arr.length;i++){
document.write("arr["+i+"] :"+arr[i]+"<br>");
}
document.write("<h2>정렬</h2>");
arr.sort();
for(i=0;i<arr.length;i++){
document.write("arr["+i+"] :"+arr[i]+"<br>");
}
document.write("<h2>역순</h2>");
arr.reverse();
for(i=0;i<arr.length;i++){
document.write("arr["+i+"] :"+arr[i]+"<br>");}


----->

length=4
join()=중앙+사이버+교육+2001
slice(1,3)=사이버,교육
concat=중앙,사이버,교육,2001,21C,실전자바스크립트
reverse=2001,교육,사이버,중앙
sort=10,20,30,40,50


2> 문자열을 처리하는 String 객체

 [형식]
  변수명=new String("문자열");
  ==   a="hoho";
  변수명.method
  변수명.property
 
  예)
  myMsg=new String("안녕하세요")
  myMsg.length
  document.write(myMsg.substring(0,2)); -->0<="  " >2
 
  Method---------------------------------------
  anchor() -문장이 있는 위치로 현재 페이지 이동
  charAt() -지정한 인덱스에 있는 문자 반환
    charAt(1)--> 1번째문자 반환
  indexOf() -찾는 문자열의 index의 위치를 반환
    indexOf("안")--> 위치 반환 , 없으면 -1 반환
  substring(숫자1, 숫자2)  
    -숫자1 에서 숫자2 사이의 문자열 반환
  toLowerCase() -문자열을 소문자 형태로 반환
  replace() -특정문자열을 새롭게 지정한 문자열로 대치


  예)
 
<html>

<head>

<script language="javascript">
document.write("[Top]".anchor("top")+"<p>")
document.write("중앙".link("http://www.joins.com")+"<br>")

-->[Top]
       중앙(link)


a=new String("자바스크립트 배우기")
document.write("\"자바스크립트배우기\"의 길이 : "+a.length+"<br>")
document.write("charAt(0)의 결과 : "+a.charAt(0)+"<p>")

-->"자바스크립트배우기"의 길이 : 10
      charAt(0)의 결과 : 자

document.write("concat('화이링')의 결과 : \
"+a.concat("화이링")+"<br>")
b=new String("중앙사이버교육과 함께")
document.write("concat(b,'웹사이트 만들기')의 결과: \
"+a.concat(b,"웹사이트 만들기")+"<br>")
document.write("indexOf('배')의 결과 : "+a.indexOf("배")+"<br>")
document.write("indexOf('java')의 결과 : "+a.indexOf("java")+"<p>")

-->"자바스크립트배우기"의 길이 : 10
      charAt(0)의 결과 : 자
      concat('화이링')의 결과 : 자바스크립트 배우기화이링
      concat(b,'웹사이트 만들기')의 결과: 자바스크립트 배우기중앙사이버교육과 함께웹사이트 만들기
      indexOf('배')의 결과 : 7
      indexOf('java')의 결과 : -1

c=new String("자바스크립트1 자바스크립트2")
document.write("lastIndexOf('자')의 결과: \
"+c.lastIndexOf("자")+"<br>")

-->lastIndexOf('자')의 결과: 8


document.write("slice(2,6)의 결과 : "+c.slice(2,6)+"<br>")
document.write("substr(2,6)의 결과 : "+c.substr(2,6)+"<br>")

-->slice(2,6)의 결과 : 스크립트
     substr(2,6)의 결과 : 스크립트1

document.write(("자바스크립트".big()).fontcolor("blue")+"를 ".fixed())
document.write(("중앙사이버교육".italics()).bold()+"과 ".blink())
document.write(("함께".fontsize(5)).strike()+"열심히".sup()+"배우자\
               ".sub()+"go".link("http://www.joins.com"))
document.write("<p></p><p></p><p></p><p></p><p></p><p></p><p></p>\
<br><br><br><br><br><br><br><br><br>")
document.write("[Top으로]".link("#top")+"<br>")

-->자바스크립트(색 blue,글자체 big)를(글자체 타자)
     중앙사이버교육(이테릭체)(진하게)과(넷스캡에서 깜박임)
     함께(글자에 중간에 --)열심히(위 첨자)배우자(아래 첨자) go(link)

     [Top으로]


</script>
</head>
<body>
</body>
</html>


3> 날짜와 시간을 다루는 Date객체
 [형식]
  Date객체명=new Date(); # 
객체를 새로 생성하는 거니까 new를 사용해주어야한다.
  Date객체명.method

 예)
 today=new Date(); //today <-- 현재 접속한 클라이언트의 시간과 날짜가 저장된다
 today.getFullYear();
 today.getMonth();


 Method---------------------------
 getFullYear() -년도를 return   == getYear()(Y2k 인식 못함)
 getMonth() -달을 return (0~11 까지 리턴  +1이 필요)
 getDate() -일을 return (1~31)
 getDay() -요일을 return (0~6 숫자가 리턴 되기 때문에 바꾸어 화면에 출력)
 getHours() -시간을 return (0~23)
 getMinutes() -분 return (0~59)
 getSeconds() -초 return (0~59)
 setDate() -일을 설정
 setFullYear() -년도를 설정

--->
 
<html>

<head>

<script language="javascript">
<!--
var ex=new Date();
document.write("ex의 값: "+ex+"<br>")
document.write("오늘의 일자 : "+ex.getDate()+"<br>")
document.write("오늘의 요일 : "+ex.getDay()+"<br>")
document.write("현재 달 : "+ex.getMonth()+"<br>")
document.write("현재년도 : "+ex.getFullYear()+"<br>")
document.write("사용자 컴퓨터와 GMT상의 시간차 : "+ex.getTimezoneOffset()+"<br>")
document.write("GMT 날짜 : "+ex.toGMTString()+"<br>")
document.write("현재 날짜 시간 : "+ex.toLocaleString()+"<br>")
document.write("출력형식 :"+ex.toString()+"<br>")

time=new Date();
document.write(time.getYear()+"³â "+time.getMonth()+"¿ù "+time.getDate()+"ÀÏ "+time.getHours()+"½Ã "+time.getMinutes()+"ºÐ "); 

//-->

</script>
</head>
<body>
</body>
</html>


ex의 값: Thu Aug 14 00:06:02 UTC+0900 2008 (UTC 세계협정 표준시, GMT 그리니치 표준시)
오늘의 일자 : 14     explorer                     netscap
오늘의 요일 : 4
현재 달 : 7
현재년도 : 2008
사용자 컴퓨터와 GMT상의 시간차 : -540
GMT 날짜 : Wed, 13 Aug 2008 15:06:02 UTC
현재 날짜 시간 : 2008년 8월 14일 목요일 오전 12:06:02
출력형식 :Thu Aug 14 00:06:02 UTC+0900 2008


4> 계산을 위한 Math 객체

 [형식]
  Math.method
  Math.property (new 라는 keyword 사용하지 X)

 예)
 Math.PI(원주율)
 Math.random()
 
 property--------------------------------
 E  -자연로그인 밑으로 사용
 PI  -파이값 반환
 SQRT1_2 -1/2의 제곱근

 Method---------------------------------
 random() -0과 1사이의 난수값 반환
 ceil(x)  -x보다 크거나 가까운 정수값 반환
 abs(x)  -x의 절대값 반환
 round(x) -x와 가장 가까운 정수로 반올림
 cos(x)  -x의 cosine값 반환
 max(x,y) -x,y값 중 큰 값 반환


  --->
 
 <html>

<head>

<script language="javascript">
<!--
document.write("랜덤값 : "+Math.random()+"<br>")
document.write("1) 자연로그 밑에 사용하는 오일러 상수="+Math.E+"<br>")
document.write("2) 원주율="+Math.PI+"<br>")
document.write("3) 2의 자연로그="+Math.LN2+"<br>")
document.write("4) 10의 자연로그="+Math.LN10+"<br>")
document.write("5) 2의 제곱근="+Math.SQRT2+"<br>")
document.write("6) 1/2의 제곱근="+Math.SQRT1_2+"<br>")
document.write("7) 절대값 ="+Math.abs(-5)+"<br>")
document.write("8) 크거나 같은 가장 가까운 정수 값 반환=\
"+Math.ceil(5.3)+"<br>")
document.write("9) 작거나 같은 가장 가까운 정수 값 반환=\
"+Math.floor(5.3)+"<br>")
document.write("10) 큰 값 반환="+Math.max(15,30)+"<br>")
document.write("11) 작은 값 반환="+Math.min(15,30)+"<br>")

//-->

</script>
</head>
<body>
</body>
</html>


랜덤값 : 0.09728262491704192
1) 자연로그 밑에 사용하는 오일러 상수=2.718281828459045
2) 원주율=3.141592653589793
3) 2의 자연로그=0.6931471805599453
4) 10의 자연로그=2.302585092994046
5) 2의 제곱근=1.4142135623730951
6) 1/2의 제곱근=0.7071067811865476
7) 절대값 =5
8) 크거나 같은 가장 가까운 정수 값 반환=6
9) 작거나 같은 가장 가까운 정수 값 반환=5
10) 큰 값 반환=30
11) 작은 값 반환=15


4> 함수를 만들어 주는 Function 객체
    : 함수를 만들때 사용하는 객체

 [형식]
  변수명=new Function(전달변수1, 전달변수2....)

 예)
 test=new Function("a","b","return (a+b)")
 document.write(test(3,5))

5> 화면 해상도 및 색상 관련 객체
    :Local 컴퓨터의 화면의 해상도나 색상에 관한 정보를 알기 위한 객체

 [형식]
  screen.method

 예)
 height=screen.availheight
 document.write("화면 높이"+height)

 property-----------------------------
       (V)availHeight -실제 화면에 보여지는 화면의 높이 반환
       (V)availWidth -실제 화면에 보여지는 화면의 너비를 반환
 colorDepth -사용가능한 색상수 반환
 height  -픽셀당 화면의 높이
 width  -픽셀당 화면의 너비 반환
 pixelDepth -픽셀당 비트수 반환


6> 문자열을 숫자로 바꾸어주는 Number객체
   :문자로된 숫자 단어를 실제 숫자로 바꾸어 주는 객체

 [형식]
  Number("숫자문자열")  -New라는 연산자는 사용하지 않는다.

 예)
 Number("15")


7> true, false를 return하는 Boolean 객체
   :bool형식의 값을 가지는 객체를 만들어주는 객체

 [형식]
  변수명=new Boolean(매개변수)

 예)
 booltest=new Boolean(15)


----->

Function--------

<script language="javascript">
<!--

ex=new Function("a","b","c","return (a+b+c)/3")
document.write(ex(30,50,90)+"<br>")

ex2=new Function("a","b","c","return (a+b+c)")
document.write(ex2(30,50,90)+"<p>")

function ex3(a,b,c)
{
      document.write("ex3 함수 호출 : ")
      document.write((a+b+c)/3)
}
ex3(30,50,90)
//-->

</script>

56.666666666666664
170

ex3 함수 호출 : 56.666666666666664

Screen------------

<script language="javascript">
<!--
document.write("당신의 컴퓨터 실제화면 너비는 "+screen.availWidth+"<br>")
document.write("당신의 컴퓨터 실제화면 높이는 "+screen.availHeight+"<br>")
document.write("당신의 컴퓨터 화면 너비는 "+screen.width+"<br>")
document.write("당신의 컴퓨터 화면 높이는 "+screen.height+"<br>")
document.write("당신의 컴퓨터 화면 색상수는 "+screen.colorDepth+"<br>")
document.write("당신의 컴퓨터 화면 비트수는 "+screen.pixelDepth+"<br>")
//-->

</script>

당신의 컴퓨터 실제화면 너비는 1280
당신의 컴퓨터 실제화면 높이는 766
당신의 컴퓨터 화면 너비는 1280
당신의 컴퓨터 화면 높이는 800
당신의 컴퓨터 화면 색상수는 32
당신의 컴퓨터 화면 비트수는 undefined


Number-------------

<script language="javascript">
<!--
document.write("15+35="+(15+35)+"<br>")
document.write("\"15\"+35="+("15"+35)+"<br>")
document.write("\"15\"+\"35\"="+("15"+"35")+"<br>")
document.write("Number(15)+\"35\"="+(Number(15)+"35")+"<br>")
document.write("Number(15)+35="+(Number(15)+35)+"<br>")
document.write("Number(\"15\")+35="+(Number("15")+35)+"<br>")
document.write("Number(\"15\")+Number(\"35\")="+(Number("15")+Number("35")+"<br>"))
//-->

</script>

15+35=50
"15"+35=1535
"15"+"35"=1535
Number(15)+"35"=1535
Number(15)+35=50
Number("15")+35=50
Number("15")+Number("35")=50


Boolean----------------

<script language="javascript">
<!--
ex1=new Boolean()
document.write("1) 값을 정의하지 않았을 때="+ex1+"<br>")

ex2=new Boolean(null)
document.write("2) null값을 입력시="+ex2+"<br>")

ex3=new Boolean(0)
document.write("3) 0을 입력시="+ex3+"<br>")

ex4=new Boolean(false)
document.write("4) false를 입력시 ="+ex4+"<br>")

ex5=new Boolean(NaN)
document.write("5) NaN을 입력시="+ex5+"<br>")

ex6=new Boolean(true)
document.write("6) true를 입력시="+ex6+"<br>")

ex7=new Boolean(15)
document.write("7) 15를 입력시="+ex7+"<br>")

//-->

</script>

1) 값을 정의하지 않았을 때=false
2) null값을 입력시=false
3) 0을 입력시=false
4) false를 입력시 =false
5) NaN을 입력시=false
6) true를 입력시=true
7) 15를 입력시=true


--- 발생하는 이벤트와 관련된 EVENT 객체 ---

 

: 자바스크립트에서 발생하는 이벤트에 관한 속성 정보를 알려 주는 객체

 [형식]
  I.E(explorer) : window.event.property
                      : window.event.method
 
  N.C(netscap) : 함수의 매개변수.property
                          함수의 매개변수.method

 예)
 window.alert(event.clientX.event.clientY)

 property------------------------------
 button  -마우스를 누른 상태
 clientX  -윈도우 영역의 마우스의 X좌표
 clientY  -윈도우 영역의 마우스의 Y좌표
 keyCode -키보드가 눌렸을경우 키의 Ascii 코드값 반환
 returnValue -이벤트에서 발생한 값을 설정
 srcElement -이벤트를 발생한 객체를 설정
 screenX -전체화면에서 x좌표 설정
 screenY -전체화면에서 Y좌표 설정
 toElement -마우스 포인터가 위치해 있는 객체 설정


--->
 
<html>

<head>
<script language="javascript">
<!--
function ex(ev)
{
     alert("x좌표="+ev.clientX+","+y좌표="+ev.clientY)
}
function test(str)
{
     if(str==true)
           alert("Welcome To My Homepage ")
     else
           alert("GoodBye")
}
//-->
</script>
</head>
<body onclick="ex(event)" onload="test(true)" onunload="test(false)">
</body>

</html>


-- 이벤트 핸들러 --

이벤트명 발생대상 설 명
Abort image 이미지를 로딩하다가 멈추었을 때
Blur window, form element 입력 포커스가 이동할 때
Change text, textarea, select 내용이 변경되었을 때
Click button, radio, checkbox, submit, reset 마우스가 눌렸을 때
DblClick button, radio, checkbox, submit, reset 마우스가 두번눌렸을 때
DragDrop window 마우스를 누른 상태로 움직였을 때
Error image, window 문서나 이미지를 로딩하다 멈췄을 때
Focus window, form element 입력 포커스를 받았을 때
KeyDown document, image, link, text 키보드로 값을 입력했을 때
KeyPress document, image, link, text 키보드가 눌렸을 때
KeyUp document, image, link, text 키보드가 눌렸다 놓았을 때
Load document 문서를 로딩을 완료했을 때
MouseDown document, button, link 마우스가 눌렸을 때
MouseMove all 마우스가 움직일 때
MouseOut image map, link 마우스가 빠져나갈 때
MouseOver link 마우스 포인터가 올라왔을 때
MouseUp document, button, link 마우스를 눌렀다 놓았을 때
Move window 브라우저를 이동시킬 때
Reset form form 태그 중 reset버튼을 눌렀을 때
Resize window 브라우저의 사이즈를 변경할 때
Select text, textarea 입력창을 선택했을 때
Submit form form값을 전송할 때
Unload document 브라우저가 현재 문서에서 빠져나갈 때
 
벤트 핸들러는 이벤트명 앞에 단순히 on을 붙이면 된다. 즉, Click 이벤트를 잡아내고 싶으면 onClick이라고 하면 Click이벤트 핸들러가 되는 것이다. 이벤트는 특정한 HTML요소 즉, HTML Tag에서 발생되는 것이기 때문에 다음과 같이 표기한다.

<INPUT TYPE="button" VALUE="Click Me" onClick="func();"> 와 같이 사용하면 된다.

 

*Event : 특정한 동작이 발생 될 경우 발생되는 신호

*Event Handler : Event를 처리할수 있는 method

 Event Handler-----------------------------
 onClick   -사용자가 클릭을 했을때
 onLoad   -페이지가 메모리에 적재
 onUnload  -페이지가 메모리에서 삭제
 onMouseOver  -마우스 포인터가 영역안에 있을때
 onMouseOut  -마우스 포인터가 영역밖에 있을때
 onChange  -폼의 요소가 변경이 있을때
 onSelect  -폼요소의 일부 또는 전체를 선택할때
 onSubmit  -Submit버튼 폼을 클릭했을때


-- 자바스크립트 브라우저 내장객체 ------------------------

객체의 접근방식

<HTML>
<BODY>
<FORM NAME=fm>
<INPUT NAME=userid TYPE=text>
</FORM>
</BODY>
</HTML>
 

자바스크립트에서 userid라는 text필드를 참조하려면,
window.document.fm.userid
로 사용하면 된다.
 
위의 예에서 보면 FORM Tag의 이름이 fm이고, 그 하위에 있는 INPUT Tag는 userid가 이름이다 

 window
      |                    
      |-Frame        
      |-document - layer
      |-Location      link
      |-History        image
                                       area
                                       anchor
                                       applet
                                       plugin
                                       form ---- Textarea                 navigator
           Text                              |--Plugin
           FileUpload                     -- Mime Type
           Password
           Hidden
           Submit
           Reset
           Radio
           Checkbox
           Button
                    Select --- Option


1> window객체
: 웹브라우저에 관한 정보를 접근하기 위한 객체
navigator객체를 제외한 대부분의 객체는 window객체 하위에 포함된다. 

 [형식]
  window.속성
  window.메소드

 예)
 window.status ="안녕하세요"
 window.close()

 property---------------------------
 classes  -문서에 정의된 css 정보 가짐
 defaultsStatus  -상태바의 초기 문자열 설정
 frames   -프레임들의 배열 정보
 opener   -open() 이용하여 연 문서(V)
 parent   -상위의 window 객체 가르침(V)
 self   -현재 활성중인 창의 자신객체(V)
 status   -상태바에 문자열 출력
 tags   -문서안의 모든 태그 정보
 top   -최상위의 window 객체 가르침(V)


 method---------------------------
 close()   -open()으로 연 창 닫기
 alert()   -간단한 경고 메세지 창 보여줌
 moveBy()  -상대적인 좌표이동
 moveTo()  -절대적인 좌표이동
 open()   -새로운 창 열기
 resizeTo()  -절대적인 창의 크기 설정
 scrollBy()  -상대적인 좌표로 스크롤 이동
 setInterval()  -일정 간격으로 함수 한번 호출
 setTimeout()  -일정 간격으로 함수를 재귀 호출
 print()   -화면에 있는 내용을 프린터로 출력


---->


<html>

<head>
<script language="javascript">
<!--
function now_status()
{
    window.status="자바스크립트를 공부합시다..."
}
function new_open()
{                        //새로운 창을 html로 열어라, 새로운창의 타겟 이름(new window)
    window.open("new.html","newwindow","toolbar=no,status=yes,width=100,height=180")
    //width:크기,height:높이, toolbar=yes/no, top:위치, left: 왼쪽위치,menubar=yes/no
}
function re_size(sel)
{
    switch(sel)
    {
         case "up" :    window.moveBy(0,-20)// '-'올라 간다
                        break
         case "down" :  window.moveBy(0,20)//상대좌표, moveTo:절대 좌표
                        break
         case "left":   window.moveBy(-20,0)
                        break
         case "right":  window.moveBy(20,0)
                        break
     }
}
//-->
</script>
</head>
<body onload="now_status()">
<form>
<input type=button value="open" onclick="new_open()"><br><br>
<input type=button value="up" onclick="re_size('up')">
<input type=button value="down" onclick="re_size('down')">
<input type=button value="left" onclick="re_size('left')">
<input type=button value="right" onclick="re_size('right')">
</form>
</body>
</html>


2> 브라우저 내장객체 - history 객체

*history 객체
 :클라이언트가 방문한 URL에 관한 정보를 보여주는 객체
  문서의 이동 경로 목록을 제어하는 history 객체와
  홈페이지의 주소 정보를 관리하는 Location객체.

 [형식]
  history.속성
  history.method
 
 예)
 history.length
 history.back()//브라우저로 본 이전 페이지로 이동

 Property-----------------------------------
 length   -browser로 읽은 URL 개수 알기

 method------------------------------------
 back()   -Browser 이전 화면으로 이동
 forward()  -Browser 다음 화면으로 이동
 go()   -상대적인 숫자를 설정하여 본화면으로 이동
 (*go(-3)... -3전으로 가겠다)

---->


<html>

<head>
<script language="javascript">
<!--
    document.write(history.length)
//-->
</script>
</head>
<body>
<form>
<input type=button value="이전" onclick="history.back()">
<input type=button value="다음" onclick="history.forward()"><br><br>
<input type=button value="2단계이전" onclick="history.go(-2)">
<input type=button value="2단계다음" onclick="history.go(2)">

</form>
</body>
</html>


* location객체
 :현재 브라우저에서 보고 있는 문서의 URL주소에 관한 정보를 가지고 있는 객체

 [형식]
  location.속성
  location.method

 예)
 location.href="http://www.naver.com"
 location.reload()

 property------------------------------------
 href  -문서의 url주소를 설정하거나 알아냄
 host  -url주소의 호스트 이름과 포트 설정을 알아냄
 hostname -url주소의 호스트 이름이나 IP주소 설정을 알아냄
 port  -포트번호를 설정하거나 알아냄
 pathname -문서의 디렉토리 위치를 설정하거나 알아냄
 search  -검색엔진을 호출할때 사용

 method-------------------------------------
 reload() -현재문서를 다시 읽어 옴
 replace() -현재문서는 다른 URL문서로 바꾸어줌


--->


<html>

<head>
<script language="javascript">
<!--
function re()
{
     location.replace("http://www.ichoongang.co.kr")
}
document.write("1)href :"+location.href+"<br>") //현재가지고 있는 주소?
document.write("2)host :"+location.host+"<br>")
document.write("3)pathname :"+location.pathname+"<br>") //폴드의 경로
document.write("4)port :"+location.port+"<br>")
document.write("5)protocol :"+location.protocol+"<br>")
//-->
</script>
</head>
<body>
<form>
<input type=button value="이동" onclick="re()">
</form>
</body>
</html>


1)href :http://www.tagmania.net/java/tagnote.htm
2)host :www.tagmania.net
3)pathname :/java/tagnote.htm
4)port :
5)protocol :http:

 이동


3> 브라우저 내장객체 - navigator객체

* navigator객체
  :브라우저의 이름, 버전등 브라우저 관련 정보를 제공하는 객체

 [형식]
  navigator.속성

 예)
 navigator.appName
 navigator.appVersion

 property---------------------------------------
 appCodeName  -브라우저의 코드명 반환
 appVersion  - 현재 사용중인 브라우저의 버전 반환
 appName  - 현재 사용중인 브라우저 이름 반환
 mimeType  - MIME형식의 정보 반환
 plugins   - 플러그인 정보 반환
 platform  - 사용중인 시스템코드 반환
 userAgent  - 브라우저의 이름,버전,코드 포함하는
       문자열 반환


---->


<html>

<head>
<script language="javascript">
<!--
document.write("1) 브라우저명 ="+navigator.appName+"<br>")
document.write("2) 브라우저버전 ="+navigator.appVersion+"<br>")
document.write("3) 브라우저코드 ="+navigator.appCodeName+"<br>")
document.write("4) 브라우저 언어 ="+navigator.language+"<br>")
document.write("5) 사용시스템 ="+navigator.platform+"<br>")
document.write("6) 이름/버전 ="+navigator.userAgent+"<br>")
//-->
</script>
</head>
<body>
</body>

</html>


브라우저의 각종정보를 모두 담고있다.
for(obj in navigator){
 
 document.write(obj+":"+navigator[obj]+"<br>");
 }




1) 브라우저명 =Microsoft Internet Explorer
2) 브라우저버전 =4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2)
3) 브라우저코드 =Mozilla
4) 브라우저 언어 =undefined
5) 사용시스템 =Win32
6) 이름/버전 =Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2)


4> 브라우저 내장객체 - document객체
* document객체
  :
브라우저가 HTML 문서의 내용을 보여주는 부분이 document객체가 가리키는 부분

 [형식]
  document.속성
  document.method
 예)
 document.bgColor="yellow"
 document.write("하하하~~ 즐거운 하루")

 property----------------------------------
 alinkColor  -누르고 있는 링크 문자열 색 설정
 bgColor  -창의 배경색 설정(V)
 cookie   -쿠키를 사용할수 있게 해줌(V)
 fgColor   -글자색을 설정(V)
 images   -이미지 배열 정보(V)
 lastModified  -가장 최근에 수정한 날짜 정보
 title   -웹페이지 제목설정 및 반환(V)
 referrer   -링크된 문서의 URL 정보
 linkColor  -링크색을 설정

 method------------------------------------
 clear()   -문서의 내용을 지움
 close()   -연 문서 닫기
 getSelection()  -마우스로 drag 한 문자열 반환
 open()    -문서의 데이터를 출력 준비
 write()   -문자열을 문서에 출력(V)
 writeln()  -줄바꾸기를 포함한 문자열을
      문서에 출력


  -image객체
 : 문서에 포함되어 있는 이미지에 관한 정보를 담고 있는 객체
 
 [형식]
  document.images.속성
  document.images[배열번호]
  이미지객체명.속성


--->


<html>

<head>
<script language="javascript">
<!--
function ex(link, alink, vlink)
{
     document.linkColor=link //red
     document.alinkColor=alink //green Active링크
     document.vlinkColor=vlink // gold
}
function ex2(A, B)
{
     document.fgColor=A ; document.bgColor=B;
}
//-->
</script>
</head>
<body onload="ex('red','green','gold')">
<a href="http://www.joins.com">중앙</a><br>
<form>
<input type=button value=navy onclick="ex2('gold','navy')">
<input type=button value=white onclick="ex2('black','white')">
<font size=2>클릭하면 배경색이 바뀐다...</font>
</form>
</body>

</html>


중앙

navy    white   클릭하면 배경색이 바뀐다...


--->

<html>
<head>
<title>예제6-1</title>
</head>
<body>
마우스를 갖다대면 그림이 변해요. ^^링크도 걸리죠.
<a href="http://www.ichoongang.co.kr">
 <img src="kid.gif" border=0 name=img
 onmouseover="document.img.src='kid.gif'"
 onmouseout="document.img.src='kid.gif'"></a>
</body>
</html>


--- 자바스크립트 폼객체(입력양식) ---

*Form객체
 <form>테크의 입력 양식정보를 제어하기 위한 객체

*Text객체
 사용자로 부터 한줄을 입력받기 위한 객체

*Password객체
 비밀번호 입력양식을 위한 객체

*hidden객체
 숨겨진 입력 양식을 위한 객체

*Reset객체
 사용자로 부터 입력된 DATA를 초기화 시키는 객체

*Submit객체
 사용자로 부터 입력된 Data를 서버에 전송하기 위한 객체

*Checkbox객체
 사용자로 부터 같은 그룹에서는 하나의 입력을 받기 위한 객체

*Radio객체
 사용자로 부터 같은 그룹에서는 하나의 입력을 받기 위한 객체

*Textarea객체
 사용자로 부터 여러줄의 입력을 받기 위한 객체

*Select객체
 리스트나 콤보박스를 위한 객체


1> Form객체
- 실질적으로 가장 많이 쓰이는 객체이다. 

 [형식]
  document.폼객체명.속성
  document.폼객체명.메소드

<FORM NAME="fm1">
.........
</FORM>

<FORM NAME="fm2">
.........
</FORM>

자바스크립트에서 각 FORM 객체에 접근하기 위해서는 window.document.fm1이라고 써주면 된다. 물론 window객체는 기본으로 적용되니까 생략하여 그냥 document.fm1이라고 써주면 첫 번째 form까지 접근할 수 있는 것이다.
위의 예에서 FORM 객체가 2개가 존재하므로, 
 

document.fm1 == document.forms[0];
document.fm2 == document.forms[1]; 

 예)
 document.frm.length
 document.frm.elements

 property-------------------------------------------
 action  -<form>tag의 action속성 정보 반환
 elements -입력양식을 배열로 정의(V)
 encoding -<form>tag의 enctype속성 정보반환
 length  -입력양식의 개수를 반환
 name  -<form>tag의 name속성 반환
 target  -<form>tag의 target속성 반환
 method  -<form>tag의 method속성 반환

 method--------------------------------------------
 submit() -입력양식에 입력한 내용을 서버로 보냄(V)
 reset()  -입력양식에 입력한 내용 초기화(V)
 blur()   -특정한 텍스트 입력 양식에 커서를 제거함
 focus()   -특정한 텍스트 입력 양식에 커서를 지정함(V)
 eval()   -수식으로 되어 있는 문자열을 계산(V)
 select()  -텍스트 입력양식 안에 있는 문자열 모두 선택
 
 

<FORM NAME=fm METHOD=GET ACTION="test.asp">
    <INPUT TYPE=text NAME=txt_name>
    <SELECT NAME=sel_type>
       <OPTION> Red </OPTION>
       <OPTION> Green </OPTION>
       <OPTION> Blue </OPTION>
    </SELECT>
    <TEXTAREA NAME=txt_area></TEXTAREA>
</FORM>

document.fm.txt_name : input 태그
document.fm.sel_type : select 태그
document.fm.txt_area : textarea 태그

순서대로 elements[] 형식으로도 가능하나 비추
document.fm.txt_name == document.fm.elements[0];
document.fm.sel_name == document.fm.elements[1];
document.fm.txt_area == document.fm.elements[2]; 


 
예제)

<script >

function func(no){ //no인자값은 form태그의 func(1) 을 받아온다.

var txt = document.fm.text_name; // type=text 에서 출력되는 내용을 txt 변수에 담는다.

        switch(no){  //no가 1,2,3,4 일때의 값들이 다르다.

        case 1:         

                alert(txt.value); // txt.value는 type=text 에서 출력되는 value값이다.

                break;

        case 2:        

                txt.value=5;

                break;

        case 3:       

                txt.size=10;

                break;

        case 4:      

                txt.size=20;

                break;

        }

}

</script>

</head>

<body>

<form name=fm>

<input type=text name=text_name value=hello><p> #type=text가 아닌 button, TEXTAREA, checkbox, radio 도 된다

<div style="border:1 solid black;width:400px">

<input type=button value="현재값은" onClick="func(1)">

<input type=button value="4로바꿈" onClick="func(2)">

<input type=button value="size10으로" onClick="func(3)">

<input type=button value="size20으로" onClick="func(4)">

</div>

</form> 
 


2> Text객체

 [형식]
  document.폼객체명.text객체명.속성
  document.폼객체명.text객체명.메소드

 예)
 document.frm.txt.value="검색어를 입력하세요"
 document.frm.txt.focus()

 property-------------------------------------------
 value   -text객체에 입력한 문자열 알아냄(V)
 
 Method--------------------------------------------
 blur()   -특정한 텍스트 입력 양식에 커서를 제거함
 focus()   -특정한 텍스트 입력 양식에 커서를 지정함(V)
 eval()   -수식으로 되어 있는 문자열을 계산(V)
 select()  -텍스트 입력양식 안에 있는 문자열 모두 선택

3> Password객체
 
 [형식]
  document.폼객체명.password객체명.속성
  document.폼객체명.password객체명.메소드

 예)
 document.frm.pwtxt.value
 document.frm.pwtxt.focus()

 property---------------------------------------------
 value  -text객체에 입력한 문자열 알아냄
 
 Method----------------------------------------------
 blur()  -특정한 암호 입력 양식에 커서를 제거함
 focus()  -특정한 암호 입력 양식에 커서를 지정함
 eval()  -수식으로 되어 있는 문자열을 계산
 select() -암호 입력양식 안에 있는 문자열 모두 선택


4> hidden객체

 [형식]
  document.폼객체명.hidden객체명.속성
  document.폼객체명.hidden객체명.메소드
 
 예)
 document.frm.hidden.value
 document.frm.hidden.eval()

 property---------------------------------------------
 value  -text객체에 입력한 문자열 알아냄
 
 Method----------------------------------------------
 eval()  -수식으로 되어 있는 문자열을 계산


---->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test()
{
   var str="1] name="+document.myform.name+"\n"
   str +="2] action="+document.myform.action+"\n"
   str +="3] target="+document.myform.target+"\n"
   str +="4] method="+document.myform.method+ "\n"
   str +="5] encoding="+document.myform.encoding +"\n"
   str +="6] length="+document.myform.length
   window.alert(str)
}
function test2()
{
    if(document.myform.name.value=="")
     {
        window.alert("이름을 적어주세요")
        document.myform.name.focus();
        return false;
     }
    if(document.myform.tel.value=="")
     {
        window.alert("전화번호를 적어주세요")
        document.myform.tel.focus();
        return false;
      }
     var str2="1] 이름="+document.myform.name.value+"\n"
         str2+="2] 전화번호="+document.myform.tel.value
     window.alert(str2)
}
//-->
</script>
</head>

<body>
<form name="myform" method=post target="_self">
1] 이름 : <input type=text size=10 name="name"><br>
2] 전화번호 : <input type=text size=10 name="tel"><br><br>
<input type=button value="form정보" onclick="test()">
<input type=button value="보내기" onclick="test2()">
<input type=button value="다시" onclick="document.myform.reset()"
</body>

</html>


---->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test()
{
   var mylen=document.myform.money.value.length
   var str=document.myform.money.value

   for(var i=0; i<mylen; i++)
   {
       if((str.charAt(i) <"0") || (str.charAt(i) >"9"))
        {
            window.alert("숫자만 입력가능합니다.")
            document.myform.money.value='';
            document.myform.money.focus();
            break
         }
   }
}
function test2()
{
   if(document.myform.money.value=="")
    {
       window.alert("금액을 입력하여 주세요")
       document.myform.money.focus();
       return false
     }
     var str="금액 = "+document.myform.money.value +"원"
     window.alert(str)
}
//-->
</script>
</head>

<body>
<form name="myform">
금액 <input type=text size=10 name=money onblur="test()">*숫자만 입력가능

<input type=button value="입력" onclick="test2()">
</body>

</html>


---->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test()
{
   var str="주최="+document.myform.hide.value+"\n"
       str+="주소="+document.myform.add.value
   window.alert(str)
}
//-->
</script>
</head>

<body>
<form name=myform>
주소를 입력하세요
<input type=hidden name="hide" value="중앙사이버 교육">
<input type=text size=20 name="add">
<input type=button value="입력" onclick="test()">
</form>

</body>

</html>


5> Checkbox객체

 [형식]
  document.폼객체명.checkbox객체명.속성
  document.폼객체명.checkbox객체명.메소드

 예)
 document.frm.check.checked
 document.frm.check.focus()

 property---------------------------------------
 value  -<input>태그에서 value속성과 동일하게 적용
 checked -체크상태를 설정하거나 반환
   체크된 것은 =true
 Method----------------------------------------
 blur()  -특정한 텍스트 입력 양식에 커서를 제거함
 focus()  -특정한 텍스트 입력 양식에 커서를 지정함
 eval()  -수식으로 되어 있는 문자열을 계산
 click()  -체크박스를 클릭함


6> Radio객체

 [형식]
  document.폼객체명.radio객체명.속성
  document.폼객체명.radio객체명.메소드

 예)
 document.frm.radio.checked
 document.frm.radio.focus()

 property------------------------------------------
 value  -<input>태그에서 value속성과 동일하게 적용(V)
 length  -같은 그룹안에 있는 라디오 버튼의 개수를 반환(V)
 checked -체크상태를 설정하거나 반환(V)

 Method-------------------------------------------
 blur()  -특정한 텍스트 입력 양식에 커서를 제거함
 focus()  -특정한 텍스트 입력 양식에 커서를 지정함
 eval()  -수식으로 되어 있는 문자열을 계산
 click()  -체크박스를 클릭 함


--->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test()
{
   sel=""
   if(myform.a1.checked)
      sel+="1번 "
   if(myform.a2.checked)
      sel+="2번 "
   window.alert(sel+"그림이 맘에 드시는 군요")
//-->
</script>
</head>

<body>
<form name=myform>
맘에드는 그림을 선택하세요.<br>
<input type=checkbox name="a1"> 1.<img src="1.gif"><br><br>
<input type=checkbox name="a2"> 2.<img src="2.gif"><br><br>
<input type=checkbox name="a3"> 3.<img src="3.gif"><br><br>
<input type=button value="확인" onclick="test()">
</form>

</body>

</html>


--->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test()
{
  if(myform.ok[0].checked)
    window.alert("1번 그림이 맘에 드시는 군요")
  else if(myform.ok[1].checked)
    window.alert("2번 그림이 맘에 드시는 군요")
  else if(myform.ok[2].checked)
    window.alert("3번 그림이 맘에 드시는 군요")
  else
    window.alert("그림을 선택하지 않으셨네요.")
}
//-->
</script>
</head>

<body>
<form name=myform>
맘에드는 그림을 선택하세요.<br>
<input type="radio" name="ok"> 1.<img src="1.gif"><br><br>
<input type="radio" name="ok"> 2.<img src="2.gif"><br><br>
<input type="radio" name="ok"> 3.<img src="3.gif"><br><br>

//radio 객체 안에 있는 모든 라디오 버튼들은 name 속성이 동일합니다.
// 같은 그룹 안에서 한개만을 선택할 수 있습니다.
//이름값이 같으면 배열객체로 사용가능.

<input type=button value="확인" onclick="test()">
</form>

</body>

</html>

7> Textarea객체
 
 [형식]
  document.폼객체명.textarea객체명.속성
  document.폼객체명.textarea객체명.메소드

 예)
 document.frm.ta.value="자기소개를 하세요"
 document.frm.ta.focus()

 property-----------------------------------------
 value  -textarea객체에 입력한 문자열 알아냄
 
 Method------------------------------------------
 blur()  -특정한 텍스트 입력 양식에 커서를 제거함
 focus()  -특정한 텍스트 입력 양식에 커서를 지정함
 eval()   -수식으로 되어 있는 문자열을 계산
 select() -텍스트 입력양식 안에 있는 문자열 모두 선택


8> Select객체
 
 [형식]
  document.폼객체명.select객체명.속성
  document.폼객체명.select객체명.메소드
 
 예)
 document.frm.sel.length
 document.frm.sel.focus()

 Method------------------------------------------
 blur()  -특정한 텍스트 입력 양식에 커서를 제거함

 property-----------------------------------------
 length   -항목의 개수를 알아냄(V)
 selectedIndex  -선택된 항목의 인덱스번호를 반환(V)
 options   -<option>태그의 정보를 배열로 포함(V)
 name   -name속성과 동일하게 적용


--->


<html>

<head>
<title>연습할 제목</title>
<script language="javascript">
<!--
function test(aa)
{
   var str=""
       str +="1] 옵션수 : "+aa.options.length +"\n"
   if(aa.options.selectedIndex==-1)
       str +="2] 선택한 옵션이 없습니다."
   else
       str +="2] 선택한 옵션은 " + aa.options.selectedIndex + "\n"
   window.alert(str)
}
//-->
</script>
</head>

<body>
<form name="myform">
<select name="sel" size=4>
<option selected>자바스크립트              //selected는 우선순위를 결정
<option>자바
<option>ASP
<option>JSP
</select>
<input type=button value="확인" onclick="test(myform.sel)">
</form>

</body>

</html>


9> File객체

 [형식]
  document.폼객체명.file객체명.속성
  document.폼객체명.file객체명.메소드

 예)
 document.frm.file.value
 document.frm.file.focus()

 property-------------------------------------------
 value  -text객체의 입력한 문자열 알아냄

 Method--------------------------------------------
 blur()  -특정한 텍스트 입력 양식에 커서를 제거함
 focus()  -특정한 텍스트 입력 양식에 커서를 지정함
 eval()  -수식으로 되어 있는 문자열을 계산


--->

<html>
<head>
<script language="javascript">
<!--
function test(aa)
{
 var str=""
 str += "1] 파일명=" +aa.name +"\n"
 str += "2] 유형 =" +aa.type + "\n"
 str += "3] value=" +aa.value
 window.alert(str)
}
//-->
</script>
</head>
<body>
<form name="myform">
<input type=file name="file2"><br>
<input type=button value="확인"
onclick="test(myform.file2)">
</form>
</body>
</html>

'HTML > java script' 카테고리의 다른 글

[Javascript] location.href와 target 이용한 URL 링크 걸기  (0) 2012.10.12
윈도우객체  (0) 2012.10.12
HTML에 자바스크립트 삽입  (0) 2012.10.04
로케이션객체  (0) 2012.10.04
Posted by wrnly