이클립스 실행해서 자바프로젝트로 만들어서 컴파일 된 class파일이 

WEB-INF 폴더 밑에 classes 폴더를 만들어서 class 파일이 들어가게 변경함.

그리고 Libraries에서 Add External Jars 눌러

C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar 추가함.


web.xml 에서 

  <display-name>Welcome to 0610 Web Project </display-name>

  <description>

     Welcome to Tomcat

  </description>

  

  <servlet>

<servlet-class>GreetServlet</servlet-class>

<servlet-name>aaa</servlet-name>

  </servlet>

  <servlet-mapping>

     <servlet-name>aaa</servlet-name>

<url-pattern>/servlet/bbb</url-pattern>

  </servlet-mapping>

</web-app>

위처럼 바뀐부분만 바꿔주고


GreetServlet.java는 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;


public class GreetServlet extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/html;charset=utf-8");   //여기에 charset=utf-8을 써줘야 한글 됨.

PrintWriter out = res.getWriter();

out.println("<!DOCTYPE html><html lang=\"ko\">");

out.println("<head><title>Welcome Hello Servlet!</title>");

out.println("<meta charset='utf-8'>");

out.println("<style>");

out.println("body { background-color:yellow;font-size:1.5em;}");

out.println("div { color:blue;font-weight:900; }");

out.println("</style></head><body>");

out.println("<div>안녕하세요. 서블릿</div>");

out.println("</body></html>");

out.close();

}

}

위와 같이 써주고 저장.

여기서 0610 폴더에 src폴더에 GreetServlet.java가 있는 것이고, 0610/classes 폴더에 GreetServlet.class가 있고 0610/WEB-INF 폴더에 web.xml 파일이 있음.


C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf 폴더에서 server.xml에서

<Host name="localhost"  appBase="webapps"

            unpackWARs="true" autoDeploy="true"> 라고 써진 곳 밑에

<Context path="/0610" docBase="D:/WebHome/0610" debug="0" reloadable="true" crossContext="true" previleged="true" /> 를 붙여 넣어줌.

그리고 tomcat 서비스를 stop 후 start.

웹브라우저에서 http://localhost:8080/manager/html 로 들어가보면 /0610의 경로가 추가된 것을 볼 수 있다.

http://localhost:8080/0610/servlet/bbb 로 들어가면 안녕하세요. 서블릿 을 볼 수 있다.

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

다른 것을 추가했다면 

web.xml 은

  <display-name>Welcome to 0610 Web Project </display-name>

  <description>

     Welcome to Tomcat

  </description>

  

  <servlet>

<servlet-class>GreetServlet</servlet-class>

<servlet-name>aaa</servlet-name>

  </servlet>

  <servlet>

<servlet-class>VisitServlet</servlet-class>

<servlet-name>visit</servlet-name>

  </servlet>

  <servlet-mapping>

     <servlet-name>aaa</servlet-name>

<url-pattern>/servlet/bbb</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

     <servlet-name>visit</servlet-name>

<url-pattern>/servlet/visit</url-pattern>

  </servlet-mapping>

</web-app>

처럼 바꿔주고

VisitServlet.java 는

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;

import java.util.Date;

import java.text.SimpleDateFormat;


public class VisitServlet extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/html;charset=utf-8");

PrintWriter out = res.getWriter();

out.println("<!DOCTYPE html><html lang=\"ko\">");

out.println("<head><title>Welcome Hello Servlet!</title>");

out.println("<meta charset='utf-8'>");

out.println("<style>");

out.println("body { background-color:yellow;font-size:1.5em;}");

out.println("div { color:blue;font-weight:900; }");

out.println("span {color:red;}");

out.println("</style></head><body>");

out.println("<div>");

String pattern = "귀하가 방문한 날짜와 시간은 Y년 M월 d일 H시 m분 s초 입니다.";

SimpleDateFormat sdf = new SimpleDateFormat(pattern);

String str = sdf.format(new Date());

out.println("<span>" + str + "</span></div>");

out.println("</body></html>");

out.close();

}

}

그리고 web.xml을 바꿨으니 http://localhost:8080/manager/html 에 가면  /0610 의 경로를 Reload 해야함.(서비스 재시작 하는것보다 효율적이므로)

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

    submit 버튼을 통해 전달.

member.html

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>회원정보</title>

</head>

<body>

<form method="get" action="/0610/servlet/info"> <!-- URL Pattern(Servlet Pattern) -->

<p><label>ID : <input type="text" name="userid"></label></p>

<p><label>Password : <input type="password" name="userpwd"></label></p>

<p><label>Name : <input type="text" name="irum"></label></p>

<p><input type="submit" value="전송"></p>

</form>

</body>

</html>


GetPostServlet.java

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;


public class GetPostServlet extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

String userid = req.getParameter("userid");

String userpwd = req.getParameter("userpwd");

String irum = req.getParameter("irum");

res.setContentType("text/html;charset=utf-8");

PrintWriter out = res.getWriter();

out.println("<!DOCTYPE html><html lang=\"ko\">");

out.println("<head><title>Welcome Hello Servlet!</title>");

out.println("<meta charset='utf-8'>");

out.println("</head><body>");

out.println("<ul>");

out.println("<li>아이디 : " + userid + "</li>");

out.println("<li>패스워드 : " + userpwd + "</li>");

out.println("<li>이름 : " + irum + "</li>");

out.println("</ul>");

out.println("</body></html>");

out.close();

}

}


web.xml

  <display-name>Welcome to 0610 Web Project </display-name>

  <description>

     Welcome to Tomcat

  </description>

  

  <servlet>

<servlet-class>GreetServlet</servlet-class>

<servlet-name>aaa</servlet-name>

  </servlet>

  <servlet>

<servlet-class>VisitServlet</servlet-class>

<servlet-name>visit</servlet-name>

  </servlet>

  <servlet>

<servlet-class>GetPostServlet</servlet-class>

<servlet-name>ccc</servlet-name>

  </servlet>

  

  <servlet-mapping>

     <servlet-name>ccc</servlet-name>

<url-pattern>/servlet/info</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

     <servlet-name>aaa</servlet-name>

<url-pattern>/servlet/bbb</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

     <servlet-name>visit</servlet-name>

<url-pattern>/servlet/visit</url-pattern>

  </servlet-mapping>

</web-app>

//Get방식의 좋은점은 url을 통해 정보 변경가능.

만약에  form method="post" 으로 보내면 doPost 로 받아줘야한다. 만약 get으로 보냈는데 doPost로 받았다면 405 에러가 발생한다.

그래서 둘다 처리해주기 위해서 GetPostServlet.java에 

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

this.doPost(req, res);

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

req.setCharacterEncoding("utf-8"); //post방식만 해당

String userid = req.getParameter("userid");

이런식으로 get방식이어도 doPost를 호출하게 만들어주면 된다.

그리고 위에서 utf8로 인코딩을 셋해줘야 한글이 깨지지 않는다. 이것은 post방식만 해당된다.

그리고 get 방식은 C:\Program Files\Apache Software Foundation\Tomcat 7.0\conf\server.xml 에서

<Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" /> 를

    <Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" />  이렇게 바꿔준다

server.xml을 바꿨으니 tomcat을 재시작.

그러면 get방식도 한글이 꺠지지 않게 할 수 있다. 만약 이것이 안되면 en to ko, ko to en 방식을 사용해야함.

난 안되니 en to utf8 방법을 사용.

따라서 한글 문제를 해결한 GetPostServlet.java 는

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;


public class GetPostServlet extends HttpServlet{

private String entoutf8(String en){

String utf8 = null;

try{

utf8 = new String(en.getBytes("ISO8859_1"), "UTF-8");

}catch(java.io.UnsupportedEncodingException ex){}

return utf8;

}

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

this.doPost(req, res);

}

public void doPost(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

req.setCharacterEncoding("utf-8");   //post 방식만 해당

String userid = req.getParameter("userid");

String userpwd = req.getParameter("userpwd");

String irum = this.entoutf8(req.getParameter("irum"));

res.setContentType("text/html;charset=utf-8");

PrintWriter out = res.getWriter();

out.println("<!DOCTYPE html><html lang=\"ko\">");

out.println("<head><title>Welcome Hello Servlet!</title>");

out.println("<meta charset='utf-8'>");

out.println("</head><body>");

out.println("<ul>");

out.println("<li>아이디 : " + userid + "</li>");

out.println("<li>패스워드 : " + userpwd + "</li>");

out.println("<li>이름 : " + irum + "</li>");

out.println("</ul>");

out.println("</body></html>");

out.close();

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

정리

한글문제

1. HTML/CSS3/JavaScript

  1)저장할 때 utf-8 로

  2)charset : utf8 로

2. Servlet

  1)rendering : res.setContentType("text/html;charset=utf-8");

  2)post 방식으로 들어올 때 : req.setCharacterEncoding("utf-8");

  3)get 방식으로 들어올 때

    a. server.xml 에서 <Connector URIEncoding="utf-8">

    b. private String entoutf(String en) ... 사용할 것

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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

버츄얼 우분투 부팅

나비가 오른쪽 위로 가게하는 법.

sudo add-apt-repository ppa:createsc/3beol

sudo apt-get update

sudo apt-get upgrade 재붓

그리고 

www.apache.org -> HTTP Server -> Apache httpd 2.4.9 Released  에 Downloads 클릭.

httpd-2.4.9.tar.gz 선택해서 다운.

터미널 켜서 tar xvfz httpd-2.4.9.tar.gz

터미널에서 gcc --version 으로 gcc가 있는지 확인.

http://apr.apache.org/ 로 이동.

Apache Portable Runtime 1.5.1 Released 에서 Downloads 선택

apr-1.5.1.tar.gz

apr-util-1.5.3.tar.gz

두개 다운.

http://pcre.org/ 이동.

아무거나 눌러 https://sourceforge.net/projects/pcre/files/pcre/ (난 이걸눌렀고)

8.35 누르고 pcre-8.35.tar.gz 눌러 다운.


터미널켜서 tar xvfz apr-1.5.1.tar.gz  쳐서 알집 풀고

cd apr-1.5.1

./configure \

> --prefix=/usr/local/apr 엔터

make 엔터

sudo make install

다시 Downloads 폴더로 가서

tar xvfz apr-util-1.5.3.tar.gz 풀고

./configure \

> --prefix=/usr/local/apr-util \

> --with-apr=/usr/local/apr

make

sudo make install

다시 Downloads 폴더로 이동.

sudo apt-get install gcc-c++    -> 실패함.

그래서  sudo apt-get install g++ 로 g++깔아줌.

tar xvfz pcre-8.35.tar.gz

cd pcre-8.35

./configure \

> --prefix=/usr/local/pcre

make

sudo make install

cd ..

cd httpd-2.4.9

./configure \

> --prefix=/usr/local/apache2 \

> --with-apr=/usr/local/apr \

> --with-apr-util=/usr/local/apr-util \

> --with-pcre=/usr/local/pcre \

> --enable-mods-shared=most \

> --enable-module=so \

> --enable-rewrite

make

sudo make install

cd /usr/local/apache2

cd bin

sudo cp apachectl /etc/init.d/httpd

cd ..

cd conf

vi httpd.conf 들어가서

ServerAdmin 87minho@hanmail.net

ServerName localhost:80

    AllowOverride none 밑을 

    Allow from all 으로 

service httpd start

그리고 웹브라우저에서 localhost 하면 It works! 를 볼 수 있다.

그리고

cd /usr/local/apache2/conf 에서 sudo vi httpd.conf

DocumentRoot "/WebHome"

<Directory "/WebHome"> 이렇게 바꿔주고

index.html을 WebHome 폴더에 넣어주고 

sudo service httpd stop

sudo service httpd start

하고 웹브라우저에서 localhost 들어가면 index.html을 볼 수 있다.

sudo apt-get install gufw 로 파이어월을 켜서 80번포트를 열어 윈도우에서 웹브라우저에 아이피를 적어놓으면 된다.

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

http://tomcat.apache.org/ 접속.

Tomcat 7.0.54 Released 에서 Downloads 눌러

7.0.54 에서 Core:의 tar.gz 다운

다운로드 폴더로가서

tar xvfz apache-tomcat-7.0.54.tar.gz

sudo mv apache-tomcat-7.0.54 /usr/local/tomcat7 

sudo apt-get install openjdk-7-jre

sudo add-apt-repository ppa:nilarimogard/webupd8

sudo apt-get update

sudo apt-get install update-java

실행은 sudo update-java

java-7-openjdk 선택

cd /usr/lib/jvm 에서 선택한 openjdk 이름 확인.

cd /usr/local/tomcat7/bin

sudo gedit catalina.sh  들어가서

#!/bin/sh 밑에

JRE_HOME="usr/lib/jvm/java-7-openjdk-amd64/jre" 를 추가.

톰캣의 start를 해줌 sudo ./startup.sh

localhost:8080 들어갔는데 안됨

sudo gedit /etc/profile 에서 제일 밑에 

export CATALINA_HOME=/usr/local/tomcat7

export JRE_HOME=/usr/lib/jvm/java-7-openjdk-amd64

export PATH=$PATH:$JRE_HOME/bin:$CATALINA_HOME/bin  

를 추가함.

source /etc/profile

echo $CATALINA_HOME

cd /usr/local/tomcat7/bin/

./startup.sh 했는데 웹브라우저에서 localhost:8080 또 실패해서

www.oracle.com 이동. Downloads-java for your computer 에서 free java download 누르고

Linux x64 filesize: 44.8 MB  다운.

Downloads 폴더로 이동해서 

tar xvfz jre-7u60-linux-x64.tar.gz

sudo mv jre1.7.0_60 /usr/lib/jvm/jre1.7.0_60

cd /usr/lib/jvm

sudo update-alternatives --config java   로 몇번까지 차있는지 확인.

sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jre1.7.0_60/bin/java 3

sudo update-alternatives --config java 하고 3 을 써줘서 3번을 써준다고 선언.

java -version 하면 1.7.0_60 버전이라고 나옴.

sudo gedit /usr/local/tomcat7/bin/catalina.sh   써서

아까 추가했던 JRE_HOME 의 경로를 아래와 같이 바꿔줌.

JRE_HOME="/usr/lib/jvm/jre1.7.0_60"

그리고 sudo gedit /etc/profile 도 아래와 같이 바꿔줌.

export CATALINA_HOME=/usr/local/tomcat7

export JRE_HOME=/usr/lib/jvm/jre1.7.0_60

export PATH=$PATH:$JRE_HOME/bin:$CATALINA_HOME/bin

source /etc/profile

cd /usr/local/tomcat7/bin

sudo ./startup.sh

웹브라우저에서 localhost:8080 들어가주면 됨

이제 매니저를 깔아주면

cd ..

cd conf

sudo gedit tomcat-users.xml 들어가서

 <!.. ..> that surrounds them.

-->  밑에

<user username="admin" password="javatomcat" roles="adnib-gui,manager-gui"/>  를 넣어줌.

cd ..

cd bin

sudo ./shutdown.sh

sudo ./startup.sh


이제 manager app들어가서 homecontext.xml 을 만들어 webapps 에 넣고 하는 전에 했던거 해주고, 

방화벽 8080 열어줘서 윈도우에서 들어올 수 있는지 확인.


http://tomcat.apache.org/download-connectors.cgi  들어가서

Tomcat Connectors JK 1.2 에서 JK 1.2.40 Source Release tar.gz 다운.

tar xvfz tomcat*.tar.gz 로 알집 풀어주고

cd tomcat-connectors-1.2.40-src

cd native

./configure --with-apxs=/usr/local/apache2/bin/apxs

make

sudo make install

cd /usr/local/apache2

cd modules

ls mod_jk.so 가 있으면 잘 설치 된거임.

cd ..

cd conf

sudo gedit httpd.conf  들어가서

#LoadModule rewrite_module modules/mod_rewrite.so 밑에

LoadModule jk_module modules/mod_jk.so

JkWorkersFile conf/workers.properties

JkLogFile logs/mod_jk.log

JkLogLevel info

JkLogStampFormat "[%a %b %d %H:%M:%S %y]"

JkMount /*.jsp loadbalancer

JkMount /*servlet/* loadbalancer

를 추가해줌.

sudo gedit workers.properties  해서

worker.list=loadbalancer

worker.tomcat1.type=ajp13

worker.tomcat1.host=localhost

worker.tomcat1.port=8008

worker.tomcat1.lbfactor=1

worker.tomcat2.type=ajp13

worker.tomcat2.host=localhost

worker.tomcat2.port=8009

worker.tomcat2.lbfactor=1

worker.loadbalancer.type=lb

worker.loadbalancer.balanced_workers=tomcat1,tomcat2

작성 후 저장. 

sudo service httpd stop

sudo /usr/local/tomcat7/bin/shutdown.sh

sudo /usr/local/tomcat7/bin/startup.sh

sudo service httpd start

그리고 웹브라우저에서

http://localhost:8080/examples/jsp/jsp2/el/basic-arithmetic.jsp  해보고

8080지워서도 해보고 되나 확인.





버츄얼 윈도우에서

ftp://192.168.8.10/Apache/WebServer/에 가서 

httpd-2.2.25-win32-x86-no_ssl.msi 5.5 MB 다운.

ftp서버 말고 그냥 2.2버전 다운받으려면

http://archive.apache.org/dist/httpd/binaries/win32/ 에서

httpd-2.2.25-win32-x86-no_ssl.msi    2013-07-10 08:06  5.5M   를 다운.

설치를 시작. next-> next하다가 Networ Domain에 localhost, Server Name에 localhost, Administrator's Email Address에 아무 이메일 넣고 80번포트 사용 next.

그리고 계속 next해서 마무리.

웹브라우저에서 url에 localhost 쓰면 It works! 가 나오는 지 확인.

그리고 httpd.conf 수정(예전에 했던거 있음)

아파치 리스타트 해주고, index.html 만들어 잘되는 지 확인.


tomcat을 깔기전에 jre가 필요하기 떄문에

www.oracle.com 가서 Downloads-java for your computer 에서 free java Download 클릭하고 agree 해서 다운.

다운 다되면 경로 변경안하고 next 해서 설치 끝냄.


www.apache.org 들어가서 밑에 Tomcat 클릭

Tomcat 7.0.54 Released 버전을 Download 32-bit/64-bit Windows Service Installer 눌러 다운.

설치시작. next->I Agree->Select the type of install: Full 버전 선택해서 next->

기본포트가 8080확인(오라클과동일). windows Service Name이 Tomcat7 확인. AJP는 아파치아 톰캣을 연동해주는 역할.

User Name 에 admin , Password에 javatomcat 해주고 next->

jre가 깔려있으면 자동으로 잡혀있음. next->어디에 깔리는지 확인 후 next->

둘다 체크해제 finish 해줌.

System-Advanced Syste settings-environment variables 에서 System variables- New... 선택해서

variable name: CATALINA_HOME

variable value: C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0

해주고 ok해줌. 

관리자권한 명령프롬프트 열어서 

set catalina_home

net start tomcat7

그리고 웹브라우저에서 http://localhost:8080/ 로 실행하면 톰캣사이트로 이동됨.

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\conf 폴더에서 tomcat-users.xml 메모장으로 열어보면

내가 설정한 아이디와 비번을 볼 수 있다.

context.xml에서 보면 WEB-INF폴더에 web.xml 이 환경설정을 한다.

server.xml에서 보면 Connector port="8080" 에서 8080포트를 다른 포트로 바꿀 수 있다.

그리고  <Host name="localhost"  appBase="webapps" 에서 webapps안에 기본 페이지(index.html과 같은)가 있다는 뜻. 

webapps/ROOT/WEB-INF 폴더안에 web.xml 이 있는데 이것이 index.html 의 역할을 하는 것이다.


homecontext.xml

<Context path="" docBase="C:/WebHome" debug="0" 

   reloadable="true" crossContext="true"

   previleged="true" />


웹브라우저에서 http://localhost:8080/ 로들어가서 Host Manager 눌러 admin/ javatomcat으로 로그인하면 관리자 페이지를 볼 수 있다.

그리고 Host Manager 위에 Manager App 눌르면 매니저목록을 볼 수 있다.

/를 undeploy 버튼 눌러 사라지게하고 

Deploy 에서 Context Path 에 / 하고 XML COnfiguration file URL: C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/homecontext.xml 쓰고

Deploy 버튼을 눌러주면 웹브라우저에서 localhost:8080 을 들어가면 된다.

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT 폴더에 WEB-INF폴더를 복사해서 WebHome 폴더에 붙여넣어줌.


www.apache.org 들어가서 밑에 Tomcat 클릭. 왼쪽 Tomcat Connectors 클릭.

Tomcat Connectors JK 1.2 에서 JK 1.2.40 Source Release zip  다운. 

(http://tomcat.apache.org/connectors-doc/ 로 들어가서 binaries-windows-tomcat-connectors-1.2.40-windows-i386-httpd-2.2.x.zip 다운(우리가 아파치가 2.2버전이기 떄문에 이것을 받아야함))

알집파일에서 mod_jk.so 파일만 빼서 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\modules 폴더에 붙여넣어줌.

C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf 폴더에서 httpd.conf 파일을 열어서

#LoadModule vhost_alias_module modules/mod_vhost_alias.so 밑에 

LoadModule jk_module modules/mod_jk.so

JkWorkersFile "C:/Program Files (x86)/Apache Software Foundation/Apache2.2/conf/workers.properties"

JkLogFile "C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/logs/mod_jk.log"

JkMount /*.jsp ajp13

JkMount /*servlet/* ajp13

을 추가해줌.


workers.properties 파일은 아래와 같이 만듬

worker.list=ajp13

worker.testWorker.type=ajp13

worker.testWorker.host=localhost

worker.testWorker.port=8009


그리고 C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf 폴더에 workers.properties 파일을 만들어줌(type은 All files로) 해서 저장.

관리자권한으로 명령프롬프트를 열어서 

net stop apache2.2

net stop tomcat7

net start tomcat7

net start apache2.2

시작은 tomcat7부터 해줘야함. 

그리고 확인은 http://localhost:8080/examples/jsp/ 에서 execute 아무거나 누르고 8080포트를 80으로 바꿔서 해보면, 그대로 있어야 된거고 안되면 안된거.


그리고 방화벽을 Inbound Rules를 New Rule 해서 80번포트를 열어줌.

윈도우에서 버츄얼 윈도우로 접속을 해봄. http://192.168.89.132/examples/jsp/jsp2/el/basic-arithmetic.jsp 로 들어가지면 되는 것.



헬로월드 servlet

이클립스켜서 HelloServlet.java

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.PrintWriter;

import java.io.IOException;


public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

PrintWriter out = res.getWriter();

res.setContentType("text/html");;

out.println("<html>");

out.println("<body bgcolor='orange'>");

out.println("<font size='7' color='green'><b>Hello, Servlet</b></font>");

out.println("</body>");

out.println("</html>");

out.close();

}

}

작성 후에 

C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\lib 폴더에 servlet-api.jar 를 가져와서 add external archives 해서 추가하면 오류 사라짐.

그리고 컴파일 된 class파일을 c:\WebHome\WEB-INF 폴더에 classes 폴더를 만들어 넣어줌.

그리고 WEB-INF 폴더에 web.xml 을  

  </description>  -이 담 부분부터

  <servlet>

    <servlet-name>Hello</servlet-name>

    <servlet-class>HelloServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>Hello</servlet-name>

    <url-pattern>/servlets/servlet/aaa</url-pattern>

  </servlet-mapping>

</web-app>  -이 전 부분까지 추가함

그리고 웹브라우저에서 localhost/servlets/servlet/aaa 하면 실행된다.

Dom

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>DOM 의 조작</title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                //window.document.addEventListener("click", myclick, false);

                document.getElementsByTagName("body")[0].addEventListener("click", myclick, false);

            }

            function myclick(){

                var newElement = document.createElement("p");   //p태그 생성

                var newTextElement = document.createTextNode("이것은 자바스크립트에 의해 생성된 단락입니다.");  //노드 생성

                document.getElementsByTagName("body")[0].appendChild(newElement).appendChild(newTextElement);  //p태그에 노드를 붙임

            }

        </script>

    </head>

    <body>

        <h3>이것은 헤드라인태그입니다.</h3>

        

    </body>

</html>

//body를 클릭하면 노드값을 계속 해서 만들어줌.

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

Dom

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.onload = function(){

                document.getElementById('h3').addEventListener("click", myclick, false);

            };

            function myclick(){

                var newObj = document.createElement('p');

                var newTextElement = document.createTextNode('이것 역시 자바스크립트에 의해 생성된 단락입니다.');

                var h3 = document.getElementsByTagName('h3')[0];

                newObj.appendChild(newTextElement);  //p태그에 노드를 붙임.

                //document.getElementsByTagName("body")[0].insertBefore(newObj,  h3);

                //document.getElementsByTagName("body")[0].appendChild(newObj);

                document.getElementsByTagName("body")[0].replaceChild(newObj, h3);  //newObj는 p태그에 노드를 붙인 것을 말하며, 이것에서 h3를 바꿈.

            };

        </script>

    </head>

    <body>

        <h3 id='h3'>이것은 헤드라인입니다.</h3>

    </body>

</html>

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

Dom

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <script>

            function add(f){

                var anchor = document.createElement('a');

                //방법1.

                anchor.href = f.url.value;

                //방법2.

                /*var href = document.createAttribute('href');

                href.nodeValue = f.url.value;

                anchor.setAttributeNode(href);*/

               var siteName = document.createTextNode(f.irum.value);

               anchor.appendChild(siteName);

               var brObj = document.createElement('br');

               var result = document.getElementById('result');

               result.appendChild(anchor);

               result.appendChild(brObj);

            }

        </script>

    </head>

    <body>

        <form>

            <label>사이트명 : <br />

            <input type="text" name="irum" size="30"></label><br />

            <label>URL : <br />

            <input type="text" name="url" size="50"></label><br />

            <input type="button" value="추가" onclick="add(this.form)">

        </form>

        <div id="result"></div>

    </body>

</html>

//사이트명과 URL을 추가하면 자동으로 result 부분에 사이트명이 추가되고 그것에 URL anchor가 걸림.

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

Dom : 클릭하면 색 바뀌는. class를 바꿔가며

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <style>

            a{

                text-decoration: none;

                color:black;

                font-size:1.2em;

            }

            div{

                width:150px;

                height:50px;

                text-align:center;

            }

            div.yellow{

                background-color: yellow;

                border:4px dotted gray;

            }

            div.green{

                background-color: green;

                border:4px dotted gray;

            }

            div.pink{

                background-color: pink;

                border:4px dotted gray;

            }

        </style>

        <script>

            var box;

            window.onload = function(){

                box = document.getElementsByTagName("div");

                var touch = document.getElementsByTagName("a");

                touch[0].addEventListener("click", myclick, false);

            };

            function myclick(evt){

                var styleName = box[0].getAttribute("class");

                //alert(styleName);

                switch(styleName){

                    case "yellow": box[0].setAttribute("class", "green"); break;   //class="green"

                    case "green" : box[0].setAttribute("class", "pink"); break;

                    case "pink" : box[0].setAttribute("class", "yellow"); break;

                }

            }

        </script>

    </head>

    <body>

        <div class="yellow"><a href="#">Click Me!</a></div>

        

    </body>

</html>

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

Dom : 클릭하면 색 바뀌는 다른 방법으로. backgroundColor, borderStyle을 바꿔가며

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <style>

            a{

                text-decoration: none;

                color:black;

                font-size:1.2em;

            }

            div{

                width:150px;

                height:50px;

                text-align:center;

                background-color: yellow;

                border:4px dotted gray;

            }

        </style>

        <script>

            var box;

            var count;

            window.onload = function(){

                box = document.getElementsByTagName("div");

                var touch = document.getElementsByTagName("a");

                count = 0;

                touch[0].addEventListener("click", myclick, false);

            };

            function myclick(evt){

                count++;

                switch(count % 3){

                    case 0: box[0].style.backgroundColor= "yellow"; 

                                box[0].style.borderStyle="dotted"; break;

                    case 1 : box[0].style.backgroundColor = "pink";

                                box[0].style.borderStyle="solid"; 

                                break;

                    case 2 : box[0].style.backgroundColor = "green";

                                box[0].style.borderStyle="double"; 

                                break; 

                }

            }

        </script>

    </head>

    <body>

        <div class="yellow"><a href="#">Click Me!</a></div>

        

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

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



제품 관리 프로그램

product.js

var Product = function(상품명, 수량, 판매단가, 매입단가, 운송료){

   var 상품명 = 상품명;

   var 수량 = 수량;

   var 판매단가 = 판매단가;

   var 매입단가 = 매입단가;

   var 운송료 = 운송료;

   var 이익금;

   var 이익율; 


    this.get상품명 = function() { return 상품명; };

    this.get수량 = function() { return 수량; };

    this.get판매단가 = function() { return 판매단가; };

    this.get매입단가 = function() { return 매입단가; };

    this.get운송료 = function() { return 운송료; };

    this.get이익금 = function() { return 이익금; };

    this.get이익율 = function() { return 이익율; };

    

    this.set이익금 = function(money) { 이익금 = money; };

    this.set이익율 = function(rate) { 이익율 = rate; };   

};

product.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 제품 관리 프로그램 </title>

        <link rel="stylesheet" href="css/product.css">

        <script src="js/product.js"></script>

        <script src="js/productmgmt.js"></script>

    </head>

    <body>

        <form>

            <fieldset>

                <legend>제품데이터</legend>

                <p><label>File : <input type="file" id="fileinput"></label>

                      <input type="button" value="File Load" id="btnload">                    

                </p>

            </fieldset>

        </form>

        <hr>

        <output id="result"></output>

    </body>

</html>


productmgmt.js

var array = [];

window.addEventListener("load", setup, false);


function setup(evt){

    document.getElementById('btnload').disabled = true;

    document.getElementById('btnload').addEventListener("click", myclick, false);

    document.getElementById('fileinput').addEventListener("change", change, false);

}


function change(evt){

    document.getElementById('btnload').disabled = false;     

}


function myclick(evt){

    var fileinput = document.getElementById('fileinput');

    var file = fileinput.files[0];

    var fr = new FileReader();

    fr.onload = function(){

        readFile(fr.result);

    };

    fr.readAsText(file);  

}

function readFile(result){

    var table = "<h1>제품 데이터 목록</h1>";

    table += "<table><thead><tr><th>제품명</th><th>수량</th><th>" +

                 "판매단가</th><th>매입단가</th><th>운송료</th><th>이익금" +

                 "</th><th>이익율</th></tr></thead>";

    table += "<tbody>";

    var productArray = result.split("\n");

    for(var i = 0 ; i < productArray.length ; i++){

        table += "<tr>";

        var pArray = productArray[i].split(",");

        var p = new Product(pArray[0], parseInt(pArray[1]),

                                      parseInt(pArray[2]), parseInt(pArray[3]),

                                      parseInt(pArray[4]));

        array.push(p);

        for(var j = 0 ; j < pArray.length ; j++){

            table += "<td>";

            if(j == 0)

               table += "<span id='" + (i + 1) + "'>" + pArray[j] + "</span>";

            else 

                table += pArray[j];

            table += "</td>";

        };

        var 판매금액 = get판매금액(p.get수량(), p.get판매단가());

        var 매입금액 = get매입금액(p.get수량(), p.get매입단가());

        var 이익금 = get이익금(판매금액, 매입금액, p.get운송료());

        p.set이익금(이익금);

        var 이익율 = get이익율(이익금, 매입금액);

        p.set이익율(이익율);

        table += "<td>";

        table += p.get이익금();               

        table += "</td>";

        table += "<td>";  

        table += p.get이익율().toFixed(2);    

        table += "</td>";

        table += "</tr>";

    }

    table += "</tbody></table>";                 

    document.getElementById('result').innerHTML = table;

    for(var k = 0 ; k < document.getElementsByTagName('span').length; k++){

        document.getElementsByTagName('span')[k].addEventListener("click", myopen, false);

    }

}

function myopen(evt){

    var x = evt.screenX;

    var y = evt.screenY;

    var p = array[parseInt(evt.target.id) -1];

    var str = p.get상품명() + "," + p.get수량() + "," + p.get판매단가() + "," +

                  p.get매입단가() + "," + p.get운송료() + "," + p.get이익금() + 

                  "," + p.get이익율();

    var w = window.open("detail.html?id=" + str, "","left=" + x + ",top=" + y + ",width=200,height=250,toolbar=0,location=0,menubar=0,status=0,scrollbars=0");

}

function get판매금액(수량, 판매단가){

   return 수량 * 판매단가;

}

function get매입금액(수량, 매입단가){

   return 수량 * 매입단가;

}

function get이익금(판매금액, 매입금액, 운송료){

   return (판매금액 - (매입금액 + 운송료));

}

function get이익율(이익금, 매입금액){

   return (이익금 / 매입금액 * 100);

}


detail.html 

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>제품상세정보</title>

        <style>

            body{

                background-color:yellow;

            }

        </style>

        <script>

            window.onload = function(){

                var str = window.location.search;  //?id=dfdfdfjdd...

                var array = str.split("=");

                var newArray = array[1].split(",");

                document.getElementById('상품명').innerHTML = newArray[0];

                document.getElementById('수량').innerHTML = newArray[1];

                document.getElementById('판매단가').innerHTML = newArray[2];

                document.getElementById('매입단가').innerHTML = newArray[3];

                document.getElementById('운송료').innerHTML = newArray[4];

                document.getElementById('이익금').innerHTML = newArray[5];

                document.getElementById('이익율').innerHTML = Number(newArray[6]).toFixed(2);

            };

        </script>

    </head>

    <body>

        <ul>

            <li>상품명 : <span id="상품명"></span></li>

            <li>수량 : <span id="수량"></span></li>

            <li>판매단가 : <span id="판매단가"></span></li>

            <li>매입단가 : <span id="매입단가"></span></li>

            <li>운송료 : <span id="운송료"></span></li>

            <li>이익금 : <span id="이익금"></span></li>

            <li>이익율 : <span id="이익율"></span></li>

        </ul>

        <a href="#" onclick="javascript:self.close();">Close</a>

    </body>

</html>


product.css

fieldset{

    margin:auto;

    width:550px;

    height:70px;

    border:5px solid blue;

}

legend{

    font-size:1.5em;font-weight:bold;

}

input[type="file"]{

    font-size:1.2em;

}

input[type="button"]{

    font-size:1.2em;background-color:yellow;

}


h1{

    text-align:center;

    font-size:1.5em;

}


table{

    margin:auto;

    border-collapse: collapse;

    width:700px;

}


thead > tr{

    background-color: darkblue;

    color:white;

    height:50px;  

    border-bottom-style: double;  

}


td, th{

    border:1px solid white;

    width:100px;

}

td{

    text-align:center;

    border:1px solid black;

}


span{

    text-decoration: underline;

    color:blue;

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

dom : childNodes, nextSibling 

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                var array = [];

                var food = document.getElementById('food');

                var child = food.firstChild;

                while(child){ 

                    if(child.nodeType == 1) array.push(child.value);  //nodeType은 개발자모드로 들어가서 확인해보면 전부 1로 되어있는 것을 볼수 있다. elements-properties에서 확인 가능. 

                    child = child.nextSibling;

                }

                /*var opts = food.childNodes;

                for(var i = 0 ; i < opts.length ; i++){

                    var opt = opts.item(i);

                    if(opt.nodeType == 1) //element 라면

                        array.push(opt.value);

                }*/

                alert(array.join());

            }

           

        </script>

    </head>

    <body>

        <form>

            가장 먹고 싶은 음식은?

            <select name="food" id="food">

                <option value="라면">라면</option>

                <option value="만두">만두</option>

                <option value="피자">피자</option>

                <option value="도너츠">도너츠</option>

                <option value="팥빙수">팥빙수</option>

                <option value="치킨">치킨</option>

            </select>

            <input type="button" value="전송">

        </form>

    </body>

</html>

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

dom : attribute 사용

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.onload = function(){

               var img = document.getElementById('myimage');

               var attrs = img.attributes;

               var array = [];

               for(var i = 0 ; i < attrs.length ; i++){

                   var attr = attrs.item(i);

                   if(attr.nodeType){

                       array.push(attr.nodeName + ":" + attr.nodeValue);

                   }

               } 

               alert(array.join("\n"));

            };

        </script>

    </head>

    <body>

        <img id="myimage" src="images/jimin.jpg" height="300" 

          width="200" border="0" alt="참 예쁜 한지민">

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적 관리 프로그램

sungjuk.js

var Sungjuk = function(hakbun, irum, kor, eng, mat, edp){

   var hakbun = hakbun;

   var irum = irum;

   var kor = kor;

   var eng = eng;

   var mat = mat;

   var edp = edp;

   var sum;

   var avg;

   var grade;

   

   this.getHakbun = function() { return hakbun; };

   this.getIrum = function() { return encodeURI(irum); };

   this.getKor = function() { return kor; };

   this.getEng = function() { return eng; };

   this.getMat = function() { return mat; };

   this.getEdp = function() { return edp; };

   this.getSum = function() { return sum; };

   this.getAvg = function() { return avg; };

   this.getGrade = function() { return grade; };

   

   this.setSum = function(hab) { return sum=hab; };

   this.setAvg = function(pyn) { return avg=pyn; };

   this.setGrade = function(hakjum) { return grade=hakjum; };   

};



sungjuk.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <meta name="author" content="이민호">

        <meta name="date" content="2014-06-05 15:28">

        <meta name="objective" content="시험">

        <meta name="environment" content="Aptana Studio 3">

        <title> 성적 데이터 </title>

        <link rel="stylesheet" href="css/sungjuk.css">

        <script src="js/sungjuk.js"></script>

        <script src="js/sungjukmgmt.js"></script>

    </head>

    <body>

        <form>

            <fieldset>

                <legend>성적 데이터 파일</legend>

                <p><label>File : <input type="file" id="fileinput"></label>

                      <input type="button" value="File Load" id="btnload">                    

                </p>

            </fieldset>

        </form>

        <hr>

        <output id="result"></output>

    </body>

</html>



sungjukmgmt.js

var array = [];

window.addEventListener("load", setup, false);


function setup(evt){

    document.getElementById('btnload').disabled = true;

    document.getElementById('btnload').addEventListener("click", myclick, false);

    document.getElementById('fileinput').addEventListener("change", change, false);

}


function change(evt){

    document.getElementById('btnload').disabled = false;     

}


function myclick(evt){

    var fileinput = document.getElementById('fileinput');

    var file = fileinput.files[0];

    var fr = new FileReader();

    fr.onload = function(){

        readFile(fr.result);

    };

    fr.readAsText(file);  

}

function readFile(result){

    var table = "<h1>성적 데이터</h1>";

    table += "<table><thead><tr><th>학번</th><th>이름</th><th>" +

                 "국어</th><th>영어</th><th>수학</th><th>전산" +

                 "</th><th>총점</th><th>평균</th><th>학점</th></tr></thead>";

    table += "<tbody>";

    var sungjukArray = result.split("\n");

    for(var i = 0 ; i < sungjukArray.length ; i++){

        table += "<tr>";

        var sArray = sungjukArray[i].split("    ");

        var s = new Sungjuk(sArray[0], sArray[1],

                                      parseInt(sArray[2]), parseInt(sArray[3]),

                                      parseInt(sArray[4]), parseInt(sArray[5]));

        array.push(s);

        for(var j = 0 ; j < sArray.length ; j++){

            table += "<td>";

            if(j == 0)

               table += "<span id='" + (i + 1) + "'>" + sArray[j] + "</span>";

            else 

                table += sArray[j];

            table += "</td>";

        };

        var sum = getTotal(s.getKor(), s.getEng(), s.getMat(), s.getEdp());

        var avg = getMean(s.getKor(), s.getEng(), s.getMat(), s.getEdp());

        var hakjum = getHakjum(avg);

        s.setSum(sum);

        s.setAvg(avg);

        s.setGrade(hakjum);

        table += "<td>";

        table += s.getSum();               

        table += "</td>";

        table += "<td>";  

        table += s.getAvg().toFixed(2);    

        table += "</td>";

        table += "<td>";  

        table += s.getGrade();    

        table += "</td>";

        table += "</tr>";

    }

    table += "</tbody></table>";                 

    document.getElementById('result').innerHTML = table;

    for(var k = 0 ; k < document.getElementsByTagName('span').length; k++){

        document.getElementsByTagName('span')[k].addEventListener("click", myopen, false);

    }

}

function myopen(evt){

    var x = evt.screenX;

    var y = evt.screenY;

    var s = array[parseInt(evt.target.id) -1];

    alert(encodeURI(s.getIrum));

    var str = s.getHakbun() + "," + s.getIrum() + "," + s.getKor() + "," +

                  s.getEng() + "," + s.getMat() + "," + s.getEdp() + 

                  "," + s.getSum() + "," + s.getAvg() + "," + s.getGrade();

    var w = window.open("detail.html?id=" + str, "","left=" + x + ",top=" + y + ",width=200,height=250,toolbar=0,location=0,menubar=0,status=0,scrollbars=0");

}

function getTotal(ko,en,ma,ed){

   return ko+en+ma+ed;

}

function getMean(ko,en,ma,ed){

   return (ko+en+ma+ed)/4;

}

function getHakjum(avg){

var grade = 'F';

    switch(parseInt(avg / 10)){

        case 10:

        case 9 :  grade = 'A'; break;

        case 8 :  grade = 'B'; break;

        case 7 :  grade = 'C'; break;

        case 6 :  grade = 'D'; break;

        default :  grade = 'F';

    }

    return grade;

}



detail.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <meta name="author" content="이민호">

        <meta name="date" content="2014-06-05 15:28">

        <meta name="objective" content="시험">

        <meta name="environment" content="Aptana Studio 3">        <title>성적 데이터</title>

        <style>

            body{

                background-color:yellow;

            }

        </style>

        <script>

            window.onload = function(){

                var str = window.location.search;  //?id=dfdfdfjdd...

                var array = str.split("=");

                var newArray = array[1].split(",");

                document.getElementById('학번').innerHTML = newArray[0];

                document.getElementById('이름').innerHTML = decodeURI(newArray[1]);

                document.getElementById('국어').innerHTML = newArray[2];

                document.getElementById('영어').innerHTML = newArray[3];

                document.getElementById('수학').innerHTML = newArray[4];

                document.getElementById('전산').innerHTML = newArray[5];

                document.getElementById('총점').innerHTML = newArray[6];

                document.getElementById('평균').innerHTML = Number(newArray[7]).toFixed(2);

                document.getElementById('학점').innerHTML = newArray[8];

            };

        </script>

    </head>

    <body>

        <ol>

            <li> 학번 : <span id="학번"></span></li>

            <li> 이름 : <span id="이름"></span></li>

            <li> 국어 : <span id="국어"></span></li>

            <li> 영어 : <span id="영어"></span></li>

            <li> 수학: <span id="수학"></span></li>

            <li> 전산: <span id="전산"></span></li>

            <li> 총점 : <span id="총점"></span></li>

            <li> 평균 : <span id="평균"></span></li>

            <li> 학점 : <span id="학점"></span></li></br>

        </ul>

        <a href="#" onclick="javascript:self.close();">Close</a>

    </body>

</html>


sungjuk.css

fieldset{

    margin:auto;

    width:550px;

    height:70px;

    border:5px solid blue;

}

legend{

    font-size:1.5em;font-weight:bold;

}

input[type="file"]{

    font-size:1.2em;

}

input[type="button"]{

    font-size:1.2em;background-color:yellow;

}


h1{

    text-align:center;

    font-size:1.5em;

}


table{

    margin:auto;

    border-collapse: collapse;

    width:700px;

}


thead > tr{

    background-color: darkblue;

    color:white;

    height:50px;  

    border-bottom-style: double;  

}


td, th{

    border:1px solid white;

    width:100px;

}

td{

    text-align:center;

    border:1px solid black;

}




cookie

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Cookie Demo </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                var p = document.getElementsByTagName('p');

                if(navigator.cookieEnabled){   //브라우저가 cookie를 지원하면

                    var sum = getCookie("sum");

                    if(sum){

                        var varSum = parseInt(sum) + 1;

                        alert("Cookie's count is " + varSum);

                        if(varSum > 5){

                            document.body.style.backgroundColor = 'red';

                        }else{

                            document.body.style.backgroundColor = 'yellow';

                        }

                        setCookie("sum", varSum);

                    }else{  //쿠키를 만든 적이 없다면

                        alert("NO Cookie, Set Now!");

                        setCookie("sum", 0);

                        document.body.style.backgroundColor = 'green';

                    }

                }

            }

            function getCookie(key){

                var cookie = document.cookie;

                var startIdx = cookie.indexOf(key + "=");

                if(startIdx >= 0){  //cookie가 있다면

                   var str = cookie.substring(startIdx, cookie.length);

                   var endIdx = str.indexOf(";");

                   if(endIdx < 0){

                       endIdx = str.length;

                   }

                   str = str.substring(0, endIdx);

                   var array = str.split("=");

                   return decodeURI(array[1]);

                }else{   //cookie가 없다면

                    return null;

                }

            }

            function setCookie(key, value){

                var timeStamp = new Date(2014, 5, 4, 15, 0, 0, 0);  //6월 5일 자정까지. 2014년 6월 5일 15시 0분 0초 0밀리세컨드. GMT시간으로 해야해서. 한국시간으로 자정을 맞추기 위해.

                document.cookie = key + "=" + encodeURI(value) + ";expires=" + timeStamp.toGMTString() + ";path=/0604/";   //0604폴더에 있는, 시간은 GMT시간으로

            }

            function clearCookie(key){

                

            }

        </script>

    </head>

    <body>

        <p>result</p>

    </body>

</html>

//새로고침하면 쿠키가 1씩 증가하며 위의 정한 숫자가 되었을 때 색이 바뀜.

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

위의 cookie 카운트 숫자를 이미지로

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <meta http-equiv="Refresh" content="1">

        <title> Cookie Demo </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                var count = getCookie("count");

                if(count){

                    var tempCount = parseInt(count) + 1;

                    setCookie("count", tempCount);

                    printCount(tempCount);

                }else{  //쿠키를 만든 적이 없다면

                    printCount("1");

                    setCookie("count", 1);

                }

            }

            function getCookie(key){

                var cookie = document.cookie;

                var startIdx = cookie.indexOf(key + "=");

                if(startIdx >= 0){  //cookie가 있다면

                   var str = cookie.substring(startIdx, cookie.length);

                   var endIdx = str.indexOf(";");

                   if(endIdx < 0){

                       endIdx = str.length;

                   }

                   str = str.substring(0, endIdx);

                   var array = str.split("=");

                   return array[1];

                }else{   //cookie가 없다면

                    return null;

                }

            }

            function setCookie(key, value){

                var timeStamp = new Date(2014, 5, 5, 0, 0, 0, 0);  //6월 5일 자정까지

                document.cookie = key + "=" + value + ";expires=" + timeStamp.toGMTString();

            }

            function printCount(cnt){

                var count = document.getElementById('count');

                var str = "";

                cnt = new String(cnt);

                for(var i = 0 ; i < 5 - cnt.length ; i++){

                    str += "<img src='images/0.gif'>";

                }

                for(i = 0 ; i < cnt.length ; i++){

                    str += "<img src='images/" + cnt.charAt(i) + ".gif'>";

                }

                count.innerHTML = str;

            }

        </script>

    </head>

    <body>

        <p>방문 카운트 : <span id="count" style='color:red;font-size:2em'></span></p>

    </body>

</html>

//1초마다 새로고침되게해서 자동으로 카운트 되게만듬

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

localstorage

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                if(typeof(Storage) !== "undefined"){

                    localStorage.irum = "조성모"; //localStorage.setItem("irum", "조성모");

                    document.getElementById('result').innerHTML = localStorage.irum;

                    //localStorage.getItem("irum");

                }else{

                    document.getElementById("result").innerHTML = 

                        "<span style='color:red'>Not Support LocalStorage</span>";

                }

            }

        </script>

    </head>

    <body>

        <p id="result"></p>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

DOM

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.onload = function(){

                var Ps = document.getElementsByTagName('p');

                Ps[2].innerHTML = "이것은 세번째 단락입니다.";

            };

        </script>

    </head>

    <body>

        <h1>DOM 예제 HTML 문서</h1>

        <p>이것은 <abbr title="Document Object Model">DOM</abbr> 문서입니다.</p>

        <p>이것은 두번째 단락입니다.</p>

        <p id="console"></p>   //원래 세번째 단락이 없었으나 자바스크립트를 이용하여 값을 넣어줬음.

    </body>

</html>

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

dom 

클릭을 하면 스타일을 줘서 글씨체를 바꿔주는 코드.

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.onload = function(){

                //var Ps = document.getElementsByTagName('p');

                //Ps[2].innerHTML = "이것은 세번째 단락입니다.";

                document.getElementById('second').onclick = function(){

                   var str = document.getElementById('second').innerHTML;

                   var str1 = "<span style='font-size:2em;color:red'>";

                   str1 += str + "</span>";

                   document.getElementById('second').innerHTML = str1;

                };

            };

        </script>

    </head>

    <body>

        <h1>DOM 예제 HTML 문서</h1>

        <p>이것은 <abbr title="Document Object Model">DOM</abbr> 문서입니다.</p>

        <p id="second">이것은 두번째 단락입니다.</p>

        <p id="console"></p>

    </body>

</html>

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

dom 접근 : .getElementById, childNodes 사용

dome1demo.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <link rel="stylesheet" href="css/style.css">

        <script>

            window.onload = function(){

               var str = document.getElementById('habit').childNodes[5].lastChild.textContent;  

               document.getElementById('console').innerHTML = "세번째 좋은 습관은 " + str;  

            };

        </script>

    </head>

    <body>

        <h1>성공하는 사람들의 7가지 습관</h1>

        <ol id="habit">

            <li><span>습관 1.</span> 자신의 삶을 주도하라</li>

            <li><span>습관 2.</span> 끝을 생각하며 시작하라</li>

            <li><span>습관 3.</span> 소중한 것을 먼저하라</li>

            <li><span>습관 4.</span> 윈 - 윈을 생각하라</li>

            <li><span>습관 5.</span> 먼저 이해하고 다음에 이해시켜라</li>

            <li><span>습관 6.</span> 시너지를 내라</li>

            <li><span>습관 7.</span> 끊임없이 쇄신하라</li>

        </ol>

        <p id="console"></p>

    </body>

</html>


style.css

h1 {

    font-size:1.5em;

}

ol{

    list-style-type: none;

}

span{

    font-weight:bold;

    color:darkblue;

}

실행하면 리스트목록이 쭉 뜨고 마지막 id가 console 부분에 "세번째 좋은 습관은 소중한 것을 먼저하라" 라고 뜬다.

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

dom 접근 : getElementsByClassName 과 nextSibling - 다음 형제

domdemo2.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <link rel="stylesheet" href="css/style.css">

        <script>

            window.onload = function(){

               var str = "세번째 좋은 습관은 <";

               str += document.getElementsByClassName('mylist')[2].nextSibling.textContent;

               document.getElementById('console').innerHTML = str + ">.";

            };

        </script>

    </head>

    <body>

        <h1>성공하는 사람들의 7가지 습관</h1>

        <ol id="habit">

            <li><span class="mylist">습관 1.</span> 자신의 삶을 주도하라</li>

            <li><span class="mylist">습관 2.</span> 끝을 생각하며 시작하라</li>

            <li><span class="mylist">습관 3.</span> 소중한 것을 먼저하라</li>

            <li><span class="mylist">습관 4.</span> 윈 - 윈을 생각하라</li>

            <li><span class="mylist">습관 5.</span> 먼저 이해하고 다음에 이해시켜라</li>

            <li><span class="mylist">습관 6.</span> 시너지를 내라</li>

            <li><span class="mylist">습관 7.</span> 끊임없이 쇄신하라</li>

        </ol>

        <p id="console"></p>

    </body>

</html>


style.css

h1 {

    font-size:1.5em;

}

ol{

    list-style-type: none;

}

.mylist {

    font-weight:bold;

    color:darkblue;

}

이렇게하면 역시 마지막 console부분 출력은 세번째 좋은 습관은 < 소중한 것을 먼저하라>. 라고 뜬다.

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

dom 접근 : querySelectorAll , querySelectorAll

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> DOM Demo </title>

        <link rel="stylesheet" href="css/style.css">

        <script>

            window.onload = function(){

               var str = "세번째 좋은 습관은 <";

               //str += document.getElementsByClassName('mylist')[2].nextSibling.textContent;

               str += document.querySelectorAll("#habit")[0].querySelectorAll("li")[2].lastChild.textContent;

               document.getElementById('console').innerHTML = str + ">.";

            };

        </script>

    </head>

    <body>

        <h1>성공하는 사람들의 7가지 습관</h1>

        <ol id="habit">

            <li><span class="mylist">습관 1.</span> 자신의 삶을 주도하라</li>

            <li><span class="mylist">습관 2.</span> 끝을 생각하며 시작하라</li>

            <li><span class="mylist">습관 3.</span> 소중한 것을 먼저하라</li>

            <li><span class="mylist">습관 4.</span> 윈 - 윈을 생각하라</li>

            <li><span class="mylist">습관 5.</span> 먼저 이해하고 다음에 이해시켜라</li>

            <li><span class="mylist">습관 6.</span> 시너지를 내라</li>

            <li><span class="mylist">습관 7.</span> 끊임없이 쇄신하라</li>

        </ol>

        <p id="console"></p>

    </body>

</html>

출력은 똑같이 소중한 것을 먼저하라

function

util.js

function catchEvent(eventObj, event, eventHandler) {

if (eventObj.addEventListener) {

eventObj.addEventListener(event, eventHandler,false);

} else if (eventObj.attachEvent) {

event = "on" + event;

eventObj.attachEvent(event, eventHandler);

}

}

function cancelEvent(event) {

if (event.preventDefault) {

event.preventDefault();

event.stopPropagation();

} else {

event.returnValue = false;

event.cancelBubble = true;

}

}


functiondemo.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Function Demo </title>

        <script src="js/util.js"></script>

        <script>

            catchEvent(window, "load", setup);

            function setup(){

                catchEvent(document.getElementById('btnCalc'), "click", myclick);

            }

            function myclick(){

                var a = document.getElementById("first").value;

                var b = document.getElementById("second").value;

                document.getElementById('result').innerHTML = a + b;

            }

        </script>

    </head>

    <body>

        <input type="number" id="first"> + 

        <input type="number" id="second"> = 

        <span id="result"></span>

        <input type="button" value="계산하기" id="btnCalc">

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

select : 드롭다운

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script src="js/util.js"></script>

        <script>

            catchEvent(window, "load", setup);

            function setup(theEvent){

                catchEvent(document.getElementById('btnSubmit'), "click", myfun);

            }

            function myfun(theEvent){

                var editors = document.getElementById('editors');

                var idx = editors.selectedIndex;

                alert(editors.options[idx].value);  //선택한 옵션의 값.

            }

        </script>

    </head>

    <body>

        <form>

            <p><label for="editors">당신은 다음 중 주로 어느 에디터를 사용하십니까?</label></p>

            <p><select id="editors" name="editors">

                    <option value="none">--선택--</option>

                    <option value="메모장">메모장</option>

                    <option value="Editplus">Editplus</option>

                    <option value="Notepad++">Notepad++</option>

                    <option value="Sublime">Sublime</option>

                    <option value="Eclipse">Eclipse</option>

            </select></p>

            <p><input type="button" value="전송" id="btnSubmit"></p>

        </form>

    </body>

</html>

여기서 <select id="editors" name="editors" multiple size="6"> 로 바꿔주면 여러개 선택가능하고 한번에 보여주는 개수가 6개로 한다는 뜻.

위처럼 바꾼다면 출력부분도  아래와 같이 바꿔주면 된다.

                var str = "";

                for(var i = 0 ; i < editors.length ; i++){

                    if(editors.options[i].selected) str += editors.options[i].value + ","; 

                }

                str = str.substring(0, str.length - 1);  //마지막 , 를 뺴주기 위함.

                alert("귀하가 선택하신 에디터는 \n" + str + "\n입니다.");

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

checkbox , radiobx  

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Checkbox, Radio </title>

        <script src="js/util.js"></script>

        <script>

            catchEvent(window, "load", setup);

            function setup(theEvent){

                catchEvent(document.getElementById('male'), "click", genderCheck);

                catchEvent(document.getElementById('female'), "click", genderCheck);

                catchEvent(document.getElementById('btnHobby'), "click", hobbyClick);

            }

            function hobbyClick(theEvent){

                var str = "";

                for(var i = 0 ; i < document.forms[0].hobby.length ; i++){

                    if(document.forms[0].hobby[i].checked) 

                        str += document.forms[0].hobby[i].value + ","; 

                }

                str = str.substring(0, str.length - 1);

                alert("귀하가 선택하신 취미는 \n" + str + "\n이군요...");

            }

            function genderCheck(theEvent){

                alert(theEvent.target.value);

            }

        </script>

    </head>

    <body>

        <form>

            <fieldset>

                <legend>성별</legend>

                <p><input type="radio" id="male" name="gender" value="남자">

                      <label for="male">남자</label>&nbsp;&nbsp;

                      <input type="radio" id="female" name="gender" value="여자">

                      <label for="female">여자</label>

                </p>

            </fieldset>

            <fieldset>

                <legend>취미</legend>

                <p>

                    <input type="checkbox" name="hobby" value="낚시">낚시&nbsp;&nbsp;

                    <input type="checkbox" name="hobby" value="등산">등산&nbsp;&nbsp;

                    <input type="checkbox" name="hobby" value="독서">독서&nbsp;&nbsp;                                    

                </p>

                <p>

                    <input type="checkbox" name="hobby" value="음악감상">음악감상&nbsp;&nbsp;

                    <input type="checkbox" name="hobby" value="게임">게임&nbsp;&nbsp;

                    <input type="checkbox" name="hobby" value="코딩">코딩&nbsp;&nbsp;                                    

                </p>

                <input type="button" value="취미선택" id="btnHobby">

            </fieldset>

        </form>

    </body>

</html>

//checkbox는 각각에 이벤트를 달기보다 버튼하나로 묶어주는 것이 좋다.(여러개가 선택될 수 있으므로)

//this.value 해도 선택된 라벨의 value를 얻어올 수 있다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

개인정보 입력 (주민등록번호, 성별, 생년월일 등) (radiobox, checkbox, keyup, substr, charAt 등 사용)

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(evt){

                //document.forms[0].elements[8].addEventListener("click", myclick, false);

                document.forms[0].elements[4].addEventListener("change", mychange, false);  //이름을 안쓰고 elements의 몇번째 인지로 접근 하는 방법

                document.forms[0].elements[4].addEventListener("keyup", keyup, false);   //키보드를 눌렀다 떨어질 때 이벤트발생.

                document.forms[0].elements[5].addEventListener("keyup", keyup1, false);

            }

            function keyup1(evt){

                if(this.value.length == 7) {

                    var str = "";

                    document.forms[0].elements[6].focus();

                    if(this.value.charAt(0) == '1' || this.value.charAt(0) == '3'){

                        document.forms[0].elements[1].checked = true;

                    }else if(this.value.charAt(0) == '2' || this.value.charAt(0) == '4'){

                        document.forms[0].elements[2].checked = true;

                    }

                    //주민번호 입력하면 자동으로 생년월일과 성별 자동입력되게

                    var jumin1 = document.forms[0].elements[4].value;

                    if(this.value.charAt(0) == 1 || this.value.charAt(0) == 2) str += "19";

                    else str +="20";

                    str += jumin1.substr(0,2) + "-" + jumin1.substr(2,2) + "-" + jumin1.substr(4,2);

                    document.forms[0].elements[3].value = str;   

                    //alert(str);                 

                }

            }

            function keyup(evt){

                var jumin1 = this.value;

                if(jumin1.length == 6) document.forms[0].elements[5].focus();  //주민번호 앞자리 6자리를 다 썼을때 뒷자리로 자동이동.

            }

            function mychange(evt){

                var jumin1 = evt.target.value;

                if(jumin1.length != 6 || !jumin1){

                    alert("첫번째 주민번호의 값이 없거나 형식에 일치하지 않습니다.");

                    document.forms[0].elements[4].focus();

                    return false;

                }

                for(var i = 0 ; i < jumin1.length ; i++){

                    if(isNaN(jumin1.charAt(i))) {

                        alert("숫자를 넣으세요.");

                        document.forms[0].elements[4].focus();

                        return false;

                    }

                }

                //alert(jumin1);

            }

            function myclick(evt){

                //alert(document.forms[0].elements[1].value);

                alert(document.forms[0].elements[3].value);

            }

        </script>

    </head>

    <body>

        <form>

            <fieldset>

                <legend>개인정보</legend>

                <p><label>성별</label>

                    <input type="radio" id="male" name="gender" value="남자">

                    <label for="male">남자</label>&nbsp;&nbsp;

                    <input type="radio" id="female" name="gender" value="여자">

                    <label for="female">여자</label>

                </p>

                <p><label>생년월일 : <input type="date"></label></p>

                <p><label>주민번호 : </label>

                    <input type="text" maxlength="6" name="jumin1" size="8"> - 

                    <input type="text" maxlength="7" name="jumin2" size="8">

                </p>

                <p><label>휴대전화 : </label>

                    <select name="hp1">

                        <option value="010">010</option>

                        <option value="011">011</option>

                        <option value="016">016</option>

                        <option value="017">017</option>

                        <option value="019">019</option>

                    </select> - 

                    <input type="tel" name="hp2" placeholder="1234-5678">                    

                </p>

                <p><input type="button" value="입력완료" name="btn"></p>

            </fieldset>

        </form>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

evt.target.innerHTML , getElementsByTagName 사용

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(evt){

                var Ps = document.getElementsByTagName("p");

                Ps[0].addEventListener("click", myOpen, false);

                Ps[1].addEventListener("click", myOpen, false);

            }

            function myOpen(evt){

                var url = "";

                switch(evt.target.innerHTML){

                    case "네이버" : url = "http://www.naver.com"; break;

                    case "구글": url = "https://www.google.com"; break;

                }

                //순서는  주소, 창이름, 옵션

                window.open(url, "w", 

                "left=400, top =200, width=500, height=400, toolbar=1, menubar=yes, location=0, resizable=0, scrollbars=1, status=yes");

            }

        </script>

    </head>

    <body>

        <p>네이버</p>

        <p>구글</p>

    </body>

</html>

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

위코드에서 닫기 추가

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            var w;

            function setup(evt){

                var Ps = document.getElementsByTagName("p");

                Ps[0].addEventListener("click", myOpen, false);

                Ps[1].addEventListener("click", myClose, false);

            }

            function myClose(evt){

                w.close();

            }

            function myOpen(evt){

                w = window.open("http://www.naver.com", "w", 

                "left=400, top =200, width=500, height=400, menubar=yes, location=0, resizable=0, scrollbars=1, status=yes");

            }

        </script>

    </head>

    <body>

        <p>네이버열기</p>

        <p>닫기</p>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

위 개인정보 소스를 새창으로 띄어 입력된 값 읽어오는 소스

windowdemo2.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            var w;

            function setup(evt){

                var btn = document.getElementById("btn");

                btn.addEventListener("click", myOpen, false);

            }

            function myOpen(evt){

                window.open("formdemo1.html", "w", 

                "left=400, top =200, width=600, height=400, menubar=yes, location=0, resizable=0, scrollbars=1, status=yes");

            }

        </script>

    </head>

    <body>

        <h1>회원정보</h1>

        <ol>

            <li>성별 : <span id="gender"></span></li>

            <li>생년월일 : <span id="birthday"></span></li>

            <li>주민번호 : <span id="jumin"></span></li>

            <li>휴대전화번호 : <span id="hp"></span></li>

        </ol>

        <input type="button" value="회원정보입력하기" id="btn">

    </body>

</html>


formdemo1.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(evt){

                document.getElementById('myclosebtn').addEventListener("click", myClose, false);

                document.getElementById("jumin1").addEventListener("keyup", keyup, false);

                document.getElementById("jumin2").addEventListener("keyup", keyup1, false);

            }

            function keyup1(evt){

                if(this.value.length == 7) {

                    var str = "";

                    document.forms[0].elements[6].focus();

                    if(this.value.charAt(0) == '1' || this.value.charAt(0) == '3'){

                        document.forms[0].elements[1].checked = true;

                    }else if(this.value.charAt(0) == '2' || this.value.charAt(0) == '4'){

                        document.forms[0].elements[2].checked = true;

                    }

                    var jumin1 = document.forms[0].elements[4].value;

                    if(this.value.charAt(0) == 1 || this.value.charAt(0) == 2) str += "19";

                    else str +="20";

                    str += jumin1.substr(0,2) + "-" + jumin1.substr(2,2) + "-" + jumin1.substr(4,2);

                    document.forms[0].elements[3].value = str;                    

                }

            }

            function keyup(evt){

                var jumin1 = this.value;

                if(jumin1.length == 6) document.forms[0].elements[5].focus();

            }

            function mychange(evt){

                var jumin1 = evt.target.value;

                if(jumin1.length != 6 || !jumin1){

                    alert("첫번째 주민번호의 값이 없거나 형식에 일치하지 않습니다.");

                    document.forms[0].elements[4].focus();

                    return false;

                }

                for(var i = 0 ; i < jumin1.length ; i++){

                    if(isNaN(jumin1.charAt(i))) {

                        alert("숫자를 넣으세요.");

                        document.forms[0].elements[4].focus();

                        return false;

                    }

                }

                //alert(jumin1);

            }

            function myClose(evt){

                //opener는 부모 창을 뜻하고, self는 현재 내 창을 뜻한다.

                if(document.getElementById('male').checked) 

                    opener.document.getElementById('gender').innerHTML = "남자";

                else if(document.getElementById('female').checked) 

                    opener.document.getElementById('gender').innerHTML = "여자";

                opener.document.getElementById('birthday').innerHTML = 

                    self.document.getElementById('birthday').value;

                opener.document.getElementById('jumin').innerHTML = 

                    self.document.getElementById('jumin1').value + "-" + 

                    self.document.getElementById('jumin2').value;

                opener.document.getElementById('hp').innerHTML = 

                    self.document.getElementById('hp1').options[self.document.getElementById('hp1').selectedIndex].value + 

                    "-" + self.document.getElementById('hp2').value;

                    

                //confirm 을 이용해서 확인창을 띄움.

                if(window.confirm("정말 창을 닫으시겠습니까?"))

                    self.close();

                else

                      self.location.href ="";

            }

        </script>

    </head>

    <body>

        <form>

            <fieldset>

                <legend>개인정보</legend>

                <p><label>성별</label>

                    <input type="radio" id="male" name="gender" value="남자">

                    <label for="male">남자</label>&nbsp;&nbsp;

                    <input type="radio" id="female" name="gender" value="여자">

                    <label for="female">여자</label>

                </p>

                <p><label>생년월일 : <input type="date" id="birthday"></label></p>

                <p><label>주민번호 : </label>

                    <input type="text" maxlength="6" name="jumin1" id="jumin1" size="8"> - 

                    <input type="text" maxlength="7" name="jumin2" id="jumin2" size="8">

                </p>

                <p><label>휴대전화 : </label>

                    <select name="hp1" id="hp1">

                        <option value="010">010</option>

                        <option value="011">011</option>

                        <option value="016">016</option>

                        <option value="017">017</option>

                        <option value="019">019</option>

                    </select> - 

                    <input type="tel" name="hp2" id="hp2" placeholder="1234-5678">                    

                </p>

                <p><input type="button" value="입력완료" name="btn" id="myclosebtn"></p>

            </fieldset>

        </form>

    </body>

</html>

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

위의 windowdemo2.html 에 move 추가 : 창이 1초마다 움직이게

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            var w;

            function setup(evt){

                var btn = document.getElementById("btn");

                btn.addEventListener("click", myOpen, false);

            }

            function myOpen(evt){

                w = window.open("formdemo1.html", "w", 

                "left=0, top =0, width=600, height=400, menubar=yes, location=0, resizable=0, scrollbars=1, status=yes");

                moveWindow(evt);

            }

            function moveWindow(evt){

                w.moveBy(10, 10); //10,10의 방향으로 계속해서 움직임. 끝에 도달하면 멈춤.

                window.setTimeout(moveWindow, 1000);

            }

        </script>

    </head>

    <body>

        <h1>회원정보</h1>

        <ol>

            <li>성별 : <span id="gender"></span></li>

            <li>생년월일 : <span id="birthday"></span></li>

            <li>주민번호 : <span id="jumin"></span></li>

            <li>휴대전화번호 : <span id="hp"></span></li>

        </ol>

        <input type="button" value="회원정보입력하기" id="btn">

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

frameset 

frameparent.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <frameset cols="30%, *">

        <frame src="menu.html" name="menu" />

        <frame src="content.html" name="content" />

    </frameset>

</html>

menu.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <style>

            body {background-color:yellow}

        </style>

        <script>

            window.addEventListener('load', setup, false);

            function setup(evt){

                document.getElementById('bookmark').addEventListener('change', change, false);

            }

            function change(evt){

                var sel = document.getElementById('bookmark');

                parent.frames[1].location = sel.options[sel.selectedIndex].value;    //부모의 2번째 프레임의 위치에  선택된 값을 뿌려줌.

            }

        </script>

    </head>

    <body>

        <label>자주가는 사이트</label>

        <select id="bookmark">

            <option>--선택--</option>

            <option value="https://www.google.com">Google</option>

            <option value="https://www.yahoo.com">Yahoo</option>

            <option value="http://www.naver.com">Naver</option>

            <option value="http://www.daum.net">Daum</option>

            <option value="http://www.nate.com">Nate</option>

        </select>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

location : href는 새창으로, replace는 현재창에서 이동.

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(evt){

                document.getElementById('btn').addEventListener("click", change, false);

            }

            function change(evt){

                var age = Number(document.getElementById('age').value);

                if(age < 10){

                    window.location.href = "http://kids.daum.net/";

                }else if(age >= 10 && age < 19){

                    window.location.replace("http://jr.naver.com/");

                }else if(age >= 19){

                    window.location.href = "http://www.nec.go.kr/portal/lwMain.do";

                }//else if(age >= 65){

                  //  window.location.replace("");

                //}

            }

        </script>

    </head>

    <body>

        <p><label>Age : <input type="text" id="age"></label>

               <input type="button" id="btn">

         </p>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

history : 방문기록이라고 생각하면 됨

historydemo.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(evt){

                var As = document.getElementsByTagName('a');

                As[1].addEventListener("click", myclick, false);

                As[2].addEventListener("click", myclick1, false);

            }

            function myclick(evt){

                alert(window.history.length);

            }

            function myclick1(evt){

                window.history.go(1);

            }

        </script>

    </head>

    <body>

        <p><a href="historydemo1.html">historydemo1.html로 가기</a></p>

        <p><a href="#">history 정보보기</a></p>

        <p><a href="#">Forward</a> </p>

    </body>

</html>


historydemo1.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body bgcolor='yellow'>

        <h1>historydemo1.html</h1>

        <input type="button" onclick="javascript:history.go(-1);">뒤로가기 

    </body>

</html>

//go(-1)대신 back() 사용해도 같다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

navigator 객체

useragent : os와 브라우저에 대한 정보

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                document.getElementsByTagName('p')[0].innerHTML = navigator.userAgent;

            }

        </script>

    </head>

    <body>

        <p></p>

    </body>

</html>

출력:

Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ
















배열의 값 복사

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Function Demo </title>

    </head>

    <body>

        <script>

            function arraycopy(array){  //배열의 값복사

               var tempArray = [];

               for(var i in array) 

                  tempArray[i] = array[i];

               return tempArray; 

            }

       

            var firstArray = [1,2,3];

            var secondArray = arraycopy(firstArray);

            secondArray.push(4);

            document.write(firstArray.toString());

        </script>

    </body>

</html>

출력:

1,2,3

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

위의 secondArray에 4를 넣기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

            function copyArray(array, lastValue){

                var tempArray = [];

                for(var i in array){

                    tempArray[i] = array[i];

                    if(lastValue) tempArray.push(lastValue);

                }

                return tempArray;

            }

            var firstArray = [1,2,3];

            var secondArray = copyArray(firstArray);

            var thirdArray = copyArray(firstArray, 4);

            document.write("<p>firstArray = " + firstArray.toString() + "</p>");

            document.write("<p>secondArray = " + secondArray.toString() + "</p>");

            document.write("<p>thirdArray = " + thirdArray.toString() + "</p>");

        </script>

    </body>

</html>

출력:

firstArray = 1,2,3


secondArray = 1,2,3


thirdArray = 1,2,3,4

//만약 var thirdArray = copyArray(firstArray, 4, 5, 6); 이것으로 써서 lastvalue를 여러개를 줘서 보내도 출력은 1,2,3,4 만 나온다. 이것을 다 보내기 위해 다음처럼 한다.

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

위 코드에서 개수를 파악해서 출력함.

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>Function Demo</title>

    </head>

    <body>

        <script>

        //전달되는 인자의 갯수 파악

        function copyArray(array, lastValue){

            var tempArray = [];

            for(var i in array){

                tempArray[i] = array[i];

                //if(lastValue) tempArray.push(lastValue);

                for(var j = 1; j < arguments.length;j++){

                    tempArray[tempArray.length] = arguments[j];

                }

            }

            return tempArray;

        }

        

        var firstArray = [1,2,3];

        var secondArray = copyArray(firstArray);

        var thirdArray = copyArray(firstArray, 4, 5, 6);  //argument의 개수 총 4개임. 0 1 2 3 의 순서.

        document.write("<p>firstArray = " + firstArray.toString() + "</p>");

        document.write("<p>secondArray = " + secondArray.toString() + "</p>");

        document.write("<p>thirdArray = " + thirdArray.toString() + "</p>");

        </script>

    </body>

</html>

출력:

firstArray = 1,2,3


secondArray = 1,2,3


thirdArray = 1,2,3,6,4,5,6,4,5,6

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

전달되는 인자의 개수파악해서 값 비교

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

            function max(){

                var max = Number.NEGATIVE_INFINITY;

                for(var i = 0 ; i < arguments.length ; i++){

                    if(arguments[i] > max) max = arguments[i];

                }

                return max;

            }

            

            var maxNumber = max(4,7,2,6,100,5000,2,3);

            document.write(maxNumber);

        </script>

    </body>

</html>

출력 : 5000

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

전달된 인자 검사

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Function Demo </title>

    </head>

    <body>

        <script>

            //전달된 인자 검사

            function sum(a, b, c){

                if(arguments.length !=3) 

                    throw new Error("함수는 3개의 인자만을 사용할 수 있습니다.");

                for(var i = 0 ; i < arguments.length ; i++){

                    if(typeof arguments[i] != "number"){

                        throw new Error("전달된 인자는 모두 숫자형이어야 합니다.");

                    }  

                }

                return a + b + c;

            }

            

            try{

                document.write("<p>" + sum(2,5,9,3,5) + "</p>");

            }catch(e){

                document.write("<p style='color:red'>" + e.message + "</p>");

            }

        </script>        

    </body>

</html>

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


<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

            function check(obj){

                //document.write("<p>" + typeof obj + "</p>");

                if((obj instanceof Array) || (typeof obj == "object" && "length" in obj)){

                    return "배열";

                }else{

                    return "배열이 아니다";

                }

            };

            var array = [1,2,3];

            var arrayObject = {a:1, b:2, c:3};

            document.write("<p>" + check(array) + "</p>");

            document.write("<p>" + check(arrayObject) + "</p>");

        </script>

    </body>

</html>

출력:

배열


배열이 아니다

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

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 화시온도 -> 섭시 온도</title>

    </head>

    <body>

        <script>

            function change(화시){

                var 섭시 = Math.floor((화시 - 32) * (10/18));

                return 섭시;

            }

            document.write("<p>화시 100도는 " + change(100) + "</p>");

        </script>

    </body>

</html>

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

Anonymous Functions

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

//

            //function calc(base, height){

            //    return base * height / 2;

            //}

            var calc = new Function('base', 'height', 'return base * height / 2');  //인자를 스트링형으로 

            document.write("<p>" + calc(2, 5) + "</p>");

        </script>

    </body>

</html>

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

function

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>Array

            //방법1 정적 function

            //function calc(base, height){

            //    return base * height / 2;

            //}

            

             //방법2 anonymous function 혹은 dynamic function

            //var calc = new Function('base', 'height', 'return base * height / 2');

            //방법 3. function literal

            var calc = function(base, height){

                return base * height / 2; 

            };

            document.write("<p>" + calc(2, 5) + "</p>");

            

        </script>

    </body>

</html>

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

function

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

        window.addEventListener("load", function(){

            document.body.style.backgroundColor = 'yellow';

            }, false);

        </script>

    </head>

    <body>

        

    </body>

</html>

//이런식으로 function의 이름을 쓸 자리에 function을 써서 사용 가능.

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

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

EVENT

mouse : onmouseover / onmouseout

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <style>

            *{

                padding:0; margin:0;

            }

             p { 

                 margin-top:20px;

                 text-align:center;

               }

        </style>

        <script>

            function change(color){

                document.body.style.backgroundColor = color;

            }

        </script>

    </head>

    <body>

        <p>

        <button onmouseover="change('yellow')"  

        onmouseout="document.body.style.backgroundColor='white'">노랑</button>&nbsp;&nbsp;&nbsp;

        <button onmouseover="change('red')" 

        onmouseout="document.body.style.backgroundColor='white'">빨강</button>&nbsp;&nbsp;&nbsp;

        <button onmouseover="change('blue')" 

        onmouseout="document.body.style.backgroundColor='white'">파랑</button>&nbsp;&nbsp;&nbsp;

        <button onmouseover="change('green')" 

        onmouseout="document.body.style.backgroundColor='white'">녹색</button>

        </p>

    </body>

</html>

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

event handling

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            function check(){

                var irum = document.forms[0].irum.value;

                if(!irum || irum.length == 0) {

                    alert("이름이 빠졌습니다.");

                    document.forms[0].irum.focus();  

                    return false; //return을 false로 하면 이벤트가 발생되지않는다(아무일도 안일어남)

                } //반대로 return true를 하면 이벤트 발생.(안쓰는거랑같음)

            }

        </script>

    </head>

    <body>

        <form method="get" action="test.jsp">

            <input type="text" name="irum">&nbsp;

            <button type="button" onclick="check()">서버로 전송</button>

            

        </form>

    </body>

</html>

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

this

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <script>

            function check(){

                alert(document.forms[0].irum.value);

            }

        </script>

    </head>

    <body>

        <form>

            <p><label>이름 : <input type="text" name="irum" id="irum"></label></p>

            <p><input type="button" value="전송" onclick="check()"></p>

        </form>

    </body>

</html>

위가 지금까지 썼던 코드 방식.

onclick="check(this)" 을 이렇게 쓰고 

function check(t){  //여기서 t는 전송버튼

                alert(t.value);

            }

이렇게 바꿔서 실행하면 전송 버튼의 값인 전송이 출력됨.

onclick="check(this.form)" 이렇게 쓰고

     function check(f){  //여기서 f는 전송버튼의 form. 

                alert(f.irum.value);

            }

위와 같이 변형하여 실행하면 텍스트박스의 값을 출력한다.

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

위의 노랑 빨강 파랑 녹색 의 색이 변하는 코드는 dom level 0 이었다. dom level 2로 바꿔보면 

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <style>

            *{

                padding:0; margin:0;

            }

             p { 

                 margin-top:20px;

                 text-align:center;

               }

        </style>

        <script src="js/util.js"></script>

        <script>

            catchEvent(window, "load", init);

            function init(){

                catchEvent(document.getElementById('yellow'), "click", change);

                catchEvent(document.getElementById('red'), "click", change);

                catchEvent(document.getElementById('blue'), "click", change);

                catchEvent(document.getElementById('green'), "click", change);

            }

            function change(){

                document.body.style.backgroundColor = this.id;

            }

        </script>

    </head>

    <body>

        <p>

        <button id="yellow">노랑</button>&nbsp;&nbsp;&nbsp;

        <button id="red">빨강</button>&nbsp;&nbsp;&nbsp;

        <button id="blue">파랑</button>&nbsp;&nbsp;&nbsp;

        <button id="green">녹색</button>

        </p>

    </body>

</html>


util.js : 여기서는 if 는 비ms , else if에서는 윈도우.

function catchEvent(eventObj, event, eventHandler) {

if (eventObj.addEventListener) {  //비ms에서 사용

eventObj.addEventListener(event, eventHandler,false);

} else if (eventObj.attachEvent) {  //윈도우즈에서 사용

event = "on" + event;

eventObj.attachEvent(event, eventHandler);

}

}

function cancelEvent(event) {

if (event.preventDefault) {

event.preventDefault();  //비ms, dom2에서 사용

event.stopPropagation();  //비ms,dom0에서 사용

} else {

event.returnValue = false;   //ms, dom2에서 사용

event.cancelBubble = true;   //ms, dom0에서 사용

}

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

array

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>Array Demo</title>

    </head>

    <body>

        <script>

            var array = [1, "two", {three:3}, [4,5], 

                              function(a,b){ return a * b; },

                              3 + 4, true];

            document.write("<p>" + array[2].three + "</p>");

            document.write("<p>" + array[3][1] + "</p>");      

            document.write("<p>" + array[4](4, 9) + "</p>");  //함수는 ()를 빼먹지 말고 써야함.       

            var aaa = array[4];   //함수포인터, 함수 변수

            document.write("<p>" + aaa(7,8) + "</p>");                 

            document.write("<ul>");                              

            for(var i in array){

                document.write("<li>" + i + " --> " + array[i] + "</li>");

            }

            document.write("</ul>");

        </script>

    </body>

</html>

출력:

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>Array Demo</title>

    </head>

    <body>

        <script>

            var array = [1, "two", {three:3}, [4,5], 

                              function(a,b){ return a * b; },

                              3 + 4, true];

            document.write("<p>" + array[2].three + "</p>");

            document.write("<p>" + array[3][1] + "</p>");      

            document.write("<p>" + array[4](4, 9) + "</p>");  //함수는 ()를 빼먹지 말고 써야함.       

            var aaa = array[4];   //함수포인터, 함수 변수

            document.write("<p>" + aaa(7,8) + "</p>");                 

            document.write("<ul>");                              

            for(var i in array){

                document.write("<li>" + i + " --> " + array[i] + "</li>");

            }

            document.write("</ul>");

        </script>

    </body>

</html>

출력:

3


5


36


56


0 --> 1

1 --> two

2 --> [object Object]

3 --> 4,5

4 --> function (a,b){ return a * b; }

5 --> 7

6 --> true

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

array

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = [1,2,3,[4,5,6],7];

            document.write("<p>" + array.length + "</p>");

            for(var i = 0 ; i < array.length ; i++){

                if(i == 3){

                    document.write("[");

                    for(var j = 0 ; j < array[3].length ; j++){

                        document.write(array[3][j] + "\t");

                    }

                    document.write("]<br>");

                }else{

                    document.write(array[i] + "<br>");

                }

            }

        </script>

    </body>

</html>

출력:

5


1

2

3

[4 5 6 ]

7

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

array

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            /*var first = [1,2,3,4,5];

            var second = first;

            first[0] = 100;

            document.write(second[0]);*/  //배열은 주소복사 이므로 100이 출력됨.

            //var array = [1,2,3,4,5];

            //array[array.length] = 6;

            //document.write(array.toString());  //1,2,3,4,5,6

            

            var array = [1,2,3,4,5];

            array[-1] = "zero";

            for(var i in array){

                document.write("<p>" + i + " --> " + array[i] + "</p>");

            }

        </script>

    </body>

</html>

출력:

0 --> 1


1 --> 2


2 --> 3


3 --> 4


4 --> 5


-1 --> zero

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

array : join 사용 (배열의 연결을 무엇을 써서 할 것인지)

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>          

            var array = [1,2,3,4,5];

            document.write("<p>" + array.toString() + "</p>");

            document.write("<p>" + array.join() + "</p>");

            document.write("<p>" + array.join(" - ") + "</p>"); 

        </script>

    </body>

</html>

출력:

1,2,3,4,5


1,2,3,4,5


1 - 2 - 3 - 4 - 5

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

array : sort

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = [4,2,5,8,3];

            array.sort();

            document.write("<p>" + array.toString() + "</p>");

            document.write("<hr>");

            array.sort(function(a, b){ return b - a; });

            document.write("<p>" + array.toString() + "</p>");

        </script>

    </body>

</html>

출력:

2,3,4,5,8


8,5,4,3,2

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

array : concat

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

           var array = [1,2,3];

           var array1 = new Array(4,5);

           var array2 = array.concat(array1);

           document.write(array2.toString());

        </script>

    </body>

</html>

출력:

1,2,3,4,5

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

array : concat 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

           var array = ["hello", "world", "Java", "Oracle"];

           document.write(array.concat([true, false], [2,3,4,5,6], [89.5, 3.14]).toString());

           

        </script>

    </body>

</html>

출력:

hello,world,Java,Oracle,true,false,2,3,4,5,6,89.5,3.14

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

array : slice

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = new Array(1,2,3,4,5,6,7,8,9);

            var demo1 = array.slice(4);

            var demo2 = array.slice(4,6);

            var demo3 = array.slice(4, -2);

            document.write("<p>" + demo1.join() + "</p>");

            document.write("<p>" + demo2.join() + "</p>");

            document.write("<p>" + demo3.join() + "</p>");

        </script> 

    </body>

</html>

출력:

5,6,7,8,9


5,6


5,6,7

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

array : splice

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = [1,2,3,4,5,6,7,8,9];

            var demo = array.splice(4, 3, "five", ["six", "seven"]);

            document.write("<p>" + demo.toString() + "</p>");

            document.write("<p>" + array.toString() + "</p>");

        </script>

    </body>

</html>

출력:

5,6,7


1,2,3,4,five,six,seven,8,9

//잘라낸 array에 대체된 것을 넣는게 아니고 demo는 걍 뽑아낸 것만 들어가네... 원본에서 그 값이 바뀌는거고.. 어렵군

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

array : push pop  뒤에서 이루어지는 입력 출력

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = new Array(1,2,3);

            array.push(4,5);

            document.write("<p>" + array.toString() + "</p>");

            document.write("<p>" + array.pop() + "</p>");

            document.write("<p>" + array.toString() + "</p>");

        </script>

    </body>

</html>

출력:

1,2,3,4,5


5


1,2,3,4

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

array : unshift shift 앞에서 이루어지는 입력 출력

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            var array = new Array(1,2,3);

            //array.push(4,5);

            array.unshift(-2,-1, 0);

            array.push(4,5);

            document.write("<p>" + array.toString() + "</p>");

            array.shift();

            document.write("<p>" + array.toString() + "</p>");

            //document.write("<p>" + array.pop() + "</p>");

            //document.write("<p>" + array.toString() + "</p>");

        </script>

    </body>

</html>

출력:

-2,-1,0,1,2,3,4,5


-1,0,1,2,3,4,5

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리프로그램 : 파일을 읽어와서 평균, 합계 구하는

arraydemo7.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

        <script src="js/main.js"></script>

        <script src="js/input.js"></script>

        <script src="js/calc.js"></script>

        <script src="js/sort.js"></script>

        <script src="js/output.js"></script>

        <script src="js/student.js"></script>

    </head>

    <body>

        <form>

            <p><label>File : <input type="file" id="myfile"></label>&nbsp;&nbsp;

            <input type="button" value="결과보기" id="output"></p>

            <hr>

        </form>

        <script>

            var myfile = document.getElementById('myfile');

            myfile.onchange = function (){

                var str = myfile.value;   //c:\fakepath\filename

                var filename = str.slice(str.lastIndexOf("\\") + 1);

                var files = this.files;

                for(var i = 0 ; i < files.length ; i++){

                    var file = files.item(i);

                    var reader = new FileReader();

                    reader.onload = function(){

                        var data = reader.result;

                        input(data);

                        calc();

                        //sort();

                    };

                    reader.readAsText(file);

                }        

            };

        </script>

    </body>

</html>


main.js

window.addEventListener("load", setup, false);

var array;

function setup(){

    array = new Array();

    document.getElementById('output').addEventListener("click", output, false);    

}

     

student.js

var Student = function(hakbun, irum, kor, eng, mat, edp){

    var hakbun = hakbun;

    var irum = irum;

    var kor = kor;

    var eng = eng;

    var mat = mat;

    var edp = edp;

    var sum;

    var avg;

    var grade;

    

    this.getHakbun = function() { return hakbun; };

    this.getIrum = function() { return irum; };

    this.getKor = function() { return kor; };

    this.getEng = function() { return eng; };

    this.getMat = function() { return mat; };

    this.getEdp = function() { return edp; };

    this.getSum = function() { return sum; };

    this.getAvg = function() { return avg; };

    this.setSum = function(total){ sum = total; };

    this.setAvg = function(average){ avg = average; };

    this.getGrade = function(){ return grade;};

    this.setGrade = function(hakjum) { grade = hakjum; };

};



input.js

function input(data){

    var array1 = data.split("\n");

    for(var i = 0 ; i < array1.length ; i++){

        var student = array1[i];  //1101     한송이     78     87     83    78

        var sArray = student.split("    ");

        var chulsu = new Student(sArray[0], sArray[1], 

                           parseInt(sArray[2]), parseInt(sArray[3]),

                           parseInt(sArray[4]), parseInt(sArray[5]));

        array.push(chulsu);  

    }

}


calc.js

function calc(){

    for(var i = 0 ; i < array.length ; i++){

        var sum = array[i].getKor() + array[i].getEng() + array[i].getMat() + array[i].getEdp();

        var avg = sum / 4.;

        array[i].setSum(sum);

        array[i].setAvg(avg);

        var grade = getGrade(avg);

        array[i].setGrade(grade);

    }

}

function getGrade(avg){

    var grade = 'F';

    switch(parseInt(avg / 10)){

        case 10:

        case 9 :  grade = 'A'; break;

        case 8 :  grade = 'B'; break;

        case 7 :  grade = 'C'; break;

        case 6 :  grade = 'D'; break;

        default :  grade = 'F';

    }

    return grade;

}


output.js

function output(){

    var str = "<!DOCTYPE html><html lang=\"ko\"><head><meta charset=\"utf-8\">";

    str += "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/style.css\">";

    str += "<title> 성적관리프로그램 </title></head><body>"; 

    str += "<table id=\"resulttable\"><caption>&lt;&lt;성적관리프로그램&gt;&gt;</caption><thead><tr><th>학번</th><th>이름</th>" +

                  "<th>국어</th><th>영어</th><th>수학</th>";

    str += "<th>전산</th><th>총점</th><th>평균</th><th>학점</th>";

    str += "</tr></thead><tbody>";

    for(var i = 0 ; i < array.length ; i++){

        str += "<tr>";

        str += "<td>" + array[i].getHakbun() + "</td>";

        str += "<td>" + array[i].getIrum() + "</td>";

        str += "<td>" + array[i].getKor() + "</td>";

        str += "<td>" + array[i].getEng() + "</td>";

        str += "<td>" + array[i].getMat() + "</td>";

        str += "<td>" + array[i].getEdp() + "</td>";

        str += "<td>" + array[i].getSum() + "</td>";

        str += "<td>" + array[i].getAvg() + "</td>";

        str += "<td>" + array[i].getGrade() + "</td>";

        str += "</tr>";

    }                      

    str += "</tbody></table></body></html>";

    var w = window.open();

    w.document.open();

    w.document.write(str);

    w.document.close();             

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

array 와 function : 숫자 입력후 sort되는

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Demo </title>

    </head>

    <body>

        <script>

            function input(a){

                for(var i = 0 ; i < a.length ; i++){

                    a[i] = parseInt(prompt("숫자를 넣어주세요"));     

                }

            };

            function sort(a){

                a.sort();

            };

            function output(a){

                document.write("<p>" + a.join() + "</p>");

            };

            var array = new Array();

            array.length = 5;

            input(array);

            document.write("<p>Before Sort</p>");

            output(array);

            sort(array);

            document.write("<p>After Sort</p>");

            output(array);

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

RegExp

우편번호 형식 검사하기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> RegExp Demo </title>

        <script>

            window.addEventListener("load", setup, false);

            

            function setup(){

                document.getElementById('mybtn').addEventListener("click", mytest, false);

            }

            function mytest(){

                var userStr = document.getElementById('zippost').value;

                var pattern = /^\d{3}-?\d{3}$/;

                if(pattern.test(userStr)){

                    alert("형식에 잘 맞습니다.");

                }else{

                    alert("우편번호 형식에 일치하지 않습니다.");

                }

            }

        </script>

    </head>

    <body>

        <form>

            <p><label>우편번호 : <input type="text" id="zippost"></label></p>

            <p><input type="button" id="mybtn" value="검사하기"></p>

        </form>

    </body>

</html>

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

RegExp

var pattern = /(fox|dog)/g;

                var str = "The quick lightbrown fox jumps over the blue dog.";

                document.write("<p>" + str.replace(pattern, "cat") + "</p>");

fox나 dog 가 나오는 것을 모두 바꿈
















for ~ in

in 으로 for문을 써서 array 접근

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> for ~ in</title>

    </head>

    <body>

        <script>

            var student = {  //object literal

                                  hakbun:'1101',

                                  irum : '한송이',

                                  kor : 100,

                                  eng : 89,

                                  mat : 77 

                                   };

            document.write("학생이름 : " + student.irum + "<br>");

            document.write("수학 점수 : " + student['mat']);  

            document.write("<p>학생 객체의 맴버 프라퍼티는 아래와 같습니다.</p>");                    

            for(var i in student){

                document.write(i + " --> " + student[i] + "<br>");

            }

            if("total" in student){

                document.write("total 프라퍼티는 있습니다.");

            }else{

                document.write("total 프라퍼티는 없습니다.");

            }

            student.total = student.kor + student.eng + student.mat;

            student.avg = student.total / 3.;

            delete student.hakbun;

            document.write("<hr>");

            for(var i in student){

                document.write(i + " --> " + student[i] + "<br>");

            }

        </script>

    </body>

</html>


출력:

학생이름 : 한송이

수학 점수 : 77

학생 객체의 맴버 프라퍼티는 아래와 같습니다.


hakbun --> 1101

irum --> 한송이

kor --> 100

eng --> 89

mat --> 77

total 프라퍼티는 없습니다.

irum --> 한송이

kor --> 100

eng --> 89

mat --> 77

total --> 266

avg --> 88.66666666666667

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

for ~ in 1

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>for ~ in</title>

    </head>

    <body>

    <script>

        var array = [100, "한송이", true, 'A', 89.555555];

        for(var i in array){  //i는 인덱스

            document.write(i + " --> " + array[i] + "<br>");

        }

    </script>

    </body>

</html>

출력:

0 --> 100

1 --> 한송이

2 --> true

3 --> A

4 --> 89.555555

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

for ~ in 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

    </head>

    <body>

        <script>

            var fruits = ["apple", "orange", "melon", "cherry", "strawberry", "grape"];

            for(var i = 0 ; i < fruits.length ; i++){

                document.write("fruits[" + i + "] = " + fruits[i] + "<br>");

            }

            document.write("<hr>");

            for(var j in fruits){  //인덱싱을 하지않고(미리 몇개 있는지 계산하며 도는 것이 아니고, 모든 것이 끝날 때까지 돈다. 이 방법이 더 빠름.

                document.write("fruits[" + j + "] = " + fruits[j] + "<br>");

            }

        </script>

    </body>

</html>

출력:

fruits[0] = apple

fruits[1] = orange

fruits[2] = melon

fruits[3] = cherry

fruits[4] = strawberry

fruits[5] = grape

fruits[0] = apple

fruits[1] = orange

fruits[2] = melon

fruits[3] = cherry

fruits[4] = strawberry

fruits[5] = grape

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

드롭다운 select , switch

이메일 형식 만들기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> </title>

        <style>

            input[type="text"]{

                border:1px solid #bbb;

            }

            input[name="emailId"]{

                text-align:right;

                width:100px;

            }

        </style>

        <script>

            window.addEventListener("load", setup, false);

            function setup(){

                document.getElementById("emailServer").addEventListener("change", change, false);

            }

            function change(){

                var email = document.getElementById('emailServer').value;

                var domain = document.getElementById('emailDomain');

                switch(email){

                    case "hanmail": domain.value = "hanmail.net"; break; 

                    case "naver": domain.value = "naver.com"; break;

                    case "nate":  domain.value = "nate.com"; break;

                    case "gmail":  domain.value = "gmail.com"; break;

                    case "user" : domain.disabled = false;

                                       domain.value = "";

                                       domain.focus();

                }

            }

        </script>

    </head>

    <body>

        <h1>Email 을 넣어주세요.</h1>

        <form>

            <p><label for="emailServer">Email : </label>

                  <input type="text" name="emailId" autofocus> @ 

                  <input type="text" id="emailDomain" name="emailDomain" disabled>

                  <select id="emailServer" name="emailServer">

                     <option value="init">--선택--</option>

                     <option value="hanmail">hanmail</option>

                     <option value="naver">naver</option>

                     <option value="nate">nate</option>

                     <option value="gmail">gmail</option>

                     <option value="user">직접입력</option>

                  </select>                 

            </p>

        </form>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체 만들기 : object literal

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

        <script>

            //1. object literal 사용하자.

            var square = {

               width:50, 

               height:100,

               color:"yellow",

               borderColor : "black",

               getArea : function(){

                   return this.width * this.height;   //반드시 this를 사용

               }

            };

            document.write("<p>사각형의 넓이는 = " + square.getArea() + "</p>");

            square.depth = 200;

            square.set = function(w, h){

                square.width = w;

                square.height = h;

            };

            square.set(10, 30);

            document.write("<p>사각형의 넓이는 = " + square.getArea() + "</p>");

            document.write("<ul>square 객체의 멤버는 아래와 같습니다.");

            for(var i in square){

                document.write("<li>" + i + " --> " + square[i] + "</li>");

                //절대로 . 연산자를 사용하면 안됨

            }

            document.write("</ul>");

        </script>

    </body>

</html>

출력 :

사각형의 넓이는 = 5000


사각형의 넓이는 = 300


square 객체의 멤버는 아래와 같습니다.

width --> 10

height --> 30

color --> yellow

borderColor --> black

getArea --> function (){ return this.width * this.height; //반드시 this를 사용 }

depth --> 200

set --> function (w, h){ square.width = w; square.height = h; }

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체 만들기 : function literal

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

    <script>

        //2. function literal

        function square(w, h){

            this.width = w;  //반드시 this를 써야 한다. 만일 var 라고 쓰면 private이다.

            this.height = h;

            this.color = "yellow";

            this.borderColor = "black";

            this.getArea = function(){

                return this.width * this.height;   //반드시 this를 사용

            };

        }

        var s = new square(50, 100);

        document.write("<p>사각형의 넓이는 " + s.getArea() + "</p>");

        if(s instanceof square){

            document.write("자식맞아<br>");

        }

        if(s instanceof Date){

            document.write("Date 객체의 인스턴스이다.<br>");

        }else{

            document.write("Date 객체의 인스턴스가 아니다.<br>");

        }

        if(s instanceof Object){

            document.write("Object 객체의 인스턴스이다.");

        }else{

            document.write("Object 객체의 인스턴스가 아니다.");

        }

    </script>

    </body>

</html>

출력:

사각형의 넓이는 5000


자식맞아

Date 객체의 인스턴스가 아니다.

Object 객체의 인스턴스이다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

출력을 새창으로 띄우기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

        <script src="js/student.js"></script>

    </head>

    <body>

    <script>

        var chulsu = new Student('1101', '한송이', 100, 89, 77, 88);

        var w = window.open();

        w.document.open();

        w.document.writeln("<!DOCTYPE html><html lang=\"en\"><head>");

        w.document.writeln("<meta charset=\"utf-8\"><title> 결과보기 </title>");

        w.document.writeln("</head><body>");

        w.document.writeln("<h1>학생정보</h1>");

        w.document.writeln("<ul type='circle'>");

        w.document.writeln("<li>학번 : " + chulsu.hakbun + "</li>");

        w.document.writeln("<li>총점 : " + chulsu.getTotal() + "</li>");

        w.document.writeln("</ul></body></html>");

        w.document.close();

    </script>

    </body>

</html>

출력: 팝업창으로 뜸.

학생정보


    학번 : 1101

    총점 : 354

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

객체만들기 : object 객체를 이용하기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 객체 만들기 </title>

    </head>

    <body>

    <script>

        /*var square = {

               width:50, 

               height:100,

               color:"yellow",

               borderColor : "black",

               getArea : function(){

                   return this.width * this.height;   //반드시 this를 사용

               }

            };*/

        //3. Object 객체를 이용하기

        var square = new Object();

        square.width = 50;

        square.height = 100;

        square.color = "yellow";

        square.borderColor = "#000";

        square.getArea = function(){

            return this.width * this.height;

        };

        square.setColor = function(foreColor){

            this.color = foreColor;

        };

        

        for(var i in square){

            document.write("<p>" + i + " --> " + square[i] + "</p>");

        }

        document.write("면적은 " + square.getArea());

    </script>

    </body>

</html>

출력: 함수의 출력은 ()를 붙여서

width --> 50


height --> 100


color --> yellow


borderColor --> #000


getArea --> function (){ return this.width * this.height; }


setColor --> function (foreColor){ this.color = foreColor; }


면적은 5000

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

number : toFixed , toExponential , toPrecision

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Number Object </title>

    </head>

    <body>

        <script>

            var n = 1234.5678;

            //var str = n.toString();

            //document.write(typeof n + "<br>");  //number

            //document.write(typeof str);  //string

            

            //var str = n.toFixed(2);  //소수점 두자리까지.   1234.57

            //var str = n.toExponential(3);  //소수점 세자리까지 지수형으로 표현 .  1.235e+3

            //var str = n.toPrecision(5);  //전체 자릿수를 5자리만. 1234.6

            var str= n.toString(8);  //8진수로.  2322.44255527175255

            

            //document.write(typeof str+"<br>");  //string.   

            document.write(str); 

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

number : 3자리 마다 콤마 찍기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Number Object </title>

    </head>

    <body>

         <script>

             var num = 123456789123456;

             var str = num.toString();  //15자리

             var money = "";

             for(var i = str.length ; i >= 0 ; i -=3){

                 if((i - 3) <= 0)

                    money = str.substr(0, i) + money;

                 else

                     money = "," + str.substr(i - 3, 3) + money;

             }

             document.write(money);

         </script>          

    </body>

</html>

출력:

123,456,789,123,456

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

String

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = new String("Hello, World");

            document.write("<p>" + str.valueOf() + "</p>");

            document.write("<p>" + str.length + "</p>");

            str = "JavaScript";

            document.write("<p>" + str.length + "</p>");

        </script>

    </body>

</html>

출력:

Hello, World


12


10

//stirng은 변할 수 있음.

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

string 1

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = '스트링 객체 연습';

            document.write(str.big() + "<br>");

            document.write(str.small() + "<br>");

            document.write(str.bold() + "<br>");

            document.write(str.italics() + "<br>");

            document.write(str.strike() + "<br>");

            document.write(str.fontcolor("red") + "<br>");

            document.write(str.fontsize(7) + "<br>");

            document.write("테스트" + str.sub() + "<br>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

string : indexOf, lastIndexOf, substr, slice

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Demo </title>

    </head>

    <body>

        <script>

            var str = new String("JavaScript was born in 1994 at Netscape");

            document.write("<p>" + str.indexOf('Netscape') + "</p>");  //몇번째 위치에 있는지

            document.write("<p>" + str.lastIndexOf("was") + "</p>");   //위와 차이는 만약 was가 두개가있을 경우에 앞에서부터 찾을지 뒤에서부터 찾을지

            document.write("<p>" + str.substr(23, 4) + "</p>");  //23번째부터 4개

            document.write("<p>" + str.slice(23, 27) + "</p>");  //23번째부터 26번째까지

        </script>

    </body>

</html>

출력:

31


11


1994


1994

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

string : split

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> String Object </title>

    </head>

    <body>

        <script>

            var str = "이름 : 조성모, 나이 : 42, 직업 : 가수";

            var array = str.split(",");

            for(var i in array){

                var array1 = array[i].split(":");

                document.write("<p>" + array1[0].fontcolor('red').fontsize(5) + " --> " + array1[1] + "</p>");

            }

        </script>

    </body>

</html>

출력:

이름 --> 조성모


나이 --> 42


직업 --> 가수

//이름, 나이, 직업은 font 준 상태

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

달력 : 월, 일 입력하면 달력 나오게

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 만년 달력 </title>

        <style>

            table{

                margin:auto;

                width:700px;

                margin-top:50px;

            }

            caption{

                font-size:1.5em;

                color:green;

                font-style:italic;

                font-weight:800;

            }

             td, th{

                border-bottom : 1px dotted #aaa;                

                width:100px;   

            }

            td{ height:70px;}

            th{

                background-color:blue;

                color:white;

                height:40px;

            }

        </style>

    </head>

    <body>

        <script>

            var str = prompt("만들고 싶은 년도와 월을 입력하세요(년과 월 사이에 콤마를 넣으세요) ");  //2014,6

            var year = str.split(",")[0];  //"2014"

            var month = str.split(",")[1];  //"6"

            var cal = new Date(parseInt(year), parseInt(month) - 1, 1);

            var space = cal.getDay(); //0:SUN

            var lastDay = function(){

               switch(month){

                   case "1":

                   case "3":

                   case "5":

                   case "7":

                   case "8":

                   case "10":

                   case "12": return 31;

                   case "4":

                   case "6":

                   case "9":

                   case "11": return 30;

                   case "2":

                    if(cal.getFullYear() % 400 == 0 || 

                               (cal.getFullYear() % 4 == 0 && cal.getFullYear() % 100 != 0))

                        return 29;

                    else return 28;

               } 

            };

            var array = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];

            document.writeln("<table>");

            document.write("<caption>" + year + "년 " + month + "월</caption>");

            document.writeln("<thead><tr>");

            for(var i = 0 ; i < array.length ; i++){

                document.write("<th>");

                document.write(array[i]);

                document.write("</th>");

            }

            document.write("</tr></thead>");

            document.write("<tbody><tr>");

            var count = 0;

            for(i = 0 ; i < space ; i++){

                document.write("<td>&nbsp;</td>");

                count++;

            }

            for(i = 1 ; i <= lastDay() ; i++){

                document.write("<td>" + i + "</td>");

                count++;

                if(count % 7 == 0){

                    document.write("</tr><tr>");

                    count = 0;

                }

            }

            for(i = 0 ; i < (7 - count) ; i++){

                document.write("<td>&nbsp;</td>");

            }

            document.writeln("</tr></tbody></table>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Date

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Date Demo </title>

    </head>

    <body>

        <script>

            var today = new Date();

            document.write("<p>" + today + "</p>");

            

            var aaa = new Date(2010, 9, 23, 06, 30, 0, 0);

            document.write("<p>" + aaa + "</p>");

            

            var bbb = Date.parse("May 29 2014 12:00:00");

            document.write("<p>" + bbb + "</p>");

            var someday = new Date(bbb);

            document.write("<p>" + someday + "</p>");

        </script>

    </body>

</html>

출력:

Thu May 29 2014 16:05:38 GMT+0900 (Korea Standard Time)


Sat Oct 23 2010 06:30:00 GMT+0900 (Korea Standard Time)


1401332400000


Thu May 29 2014 12:00:00 GMT+0900 (Korea Standard Time)

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Date 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Date Demo </title>

    </head>

    <body>

        <script>

           var today = new Date();

           var array = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];

           var str = "<p>지금은 " + today.getFullYear() + "년 " +

                         (today.getMonth() + 1) + "월 " +

                         today.getDate() + "일 " +

                         array[today.getDay()] + 

                         today.getHours() + "시 " +

                         today.getMinutes() + "분 " +

                         today.getSeconds() + "초 입니다.";

            document.write("<p>" + str + "</p>");                         

        </script>

    </body>

</html>

출력:

지금은 2014년 5월 29일 목요일16시 10분 21초 입니다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

디지털 시계 : 1초마다 refresh 되게

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <meta http-equiv="Refresh" content="1">

        <title> 디지털 시계 </title>

    </head>

    <body>

    <script>

        var now = new Date();

        var str = (now.getHours() > 12) ? (now.getHours() - 12) : now.getHours();

        str = "" + (str.length == 1) ? "0" + str : str;

        str += " : " + ((now.getMinutes().toString().length == 1) ? 

                             "0" + now.getMinutes() : now.getMinutes());

        str += " : " + ((now.getSeconds().toString().length == 1) ? 

                             "0" + now.getSeconds() : now.getSeconds()); 

        document.write("<p style='font-size:3em;font-weight:900'>");

        document.write(str + "</p>");

    </script>

    </body>

</html>

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

디지털 시계 : 1초마다 너무 함수 호출

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <!--<meta http-equiv="Refresh" content="1">-->

        <title> 디지털 시계 </title>

    </head>

    <body>

        <p id="mytime" style='font-size:3em;font-weight:900'></p>

    <script>

        window.addEventListener("load", getTimer, false);

        function getTimer(){

            var now = new Date();

            var str = (now.getHours() > 12) ? (now.getHours() - 12) : now.getHours();

            str = "" + (str.length == 1) ? "0" + str : str;

            str += " : " + ((now.getMinutes().toString().length == 1) ? 

                                 "0" + now.getMinutes() : now.getMinutes());

            str += " : " + ((now.getSeconds().toString().length == 1) ? 

                                 "0" + now.getSeconds() : now.getSeconds()); 

            document.getElementById('mytime').innerHTML = str;

            setTimeout(getTimer, 1000);

        }

        

    </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Math

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Math Object </title>

    </head>

    <body>

        <script>

            var num1 = 123.456;

            var num2 = 345.678;

            var num3 = 567.891;

            document.write("<p>123.456의 반올림값은 " + Math.round(num1) + "</p>");

            document.write("<p>345.678의 절상값은 " + Math.ceil(num2) + "</p>");

            document.write("<p>567.891의 절삭값은 " + Math.floor(num3) + "</p>");

            

            var r = 123;

            function get반지름(radius){

                return Math.floor(Math.pow(radius, 2) * Math.PI);

            }

            document.write("<p>반지름이 " + r + "cm인 원의 넓이는 ");

            document.write(get반지름(r) + "cm<sup>2</sup>입니다.</p>");

        </script>

    </body>

</html>

출력:

123.456의 반올림값은 123


345.678의 절상값은 346


567.891의 절삭값은 567


반지름이 123cm인 원의 넓이는 47529cm2입니다.

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

=======================================
D-day 계산기
index.html
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <title>우리 자기 기념일 계산기</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/script.js"></script>        
</head>
<body>
    <div id="wrapper">
    <h1>우리 자기 기념일 계산기</h1>
    <form>
        <p id="today"></p>
        <p>우리 자기 처음 만난 날은 :<br>
            <input value="2012" id="meeting_year">년 
            <select id="meeting_month">
                <option value="0">1월</option>
                <option value="1">2월</option>
                <option value="2">3월</option>
                <option value="3">4월</option>
                <option value="4">5월</option>
                <option value="5">6월</option>
                <option value="6">7월</option>
                <option value="7">8월</option>
                <option value="8">9월</option>
                <option value="9">10월</option>
                <option value="10">11월</option>
                <option value="11">12월</option>
            </select>
            <input value="1" id="meeting_day">일
            <input type="button" id="count_btn" value="계산하기">
        </p>
        <p>우리 자기는 오늘 <input id="today_count" disabled> 일 째 입니다.</p>
        <hr>
        <p>우리 자기 <input id="memorial_day"> 일 째 되는 날은?<input type="button" id="memorial_btn" value="계산하기"></p>
        <p>우리 자기의 <input id="memorial_count"> 일 째 되는 날은 <input id="memorial_date"> 입니다.</p>
    </form>
    </div>
</body>
</html>

scripts.js
// 페이지 로딩이 끝나면 init 함수를 콜백
window.addEventListener('load', init, false);

function init() {
// Date 객체 today를 오늘 날짜로 생성
var today = new Date();
// 
var countDayOutput = document.getElementById('today_count');
var memorialCountOutput = document.getElementById('memorial_count');
var memorialDayOutput = document.getElementById('memorial_date');
// 사용자가 입력한 날이 셋팅되었는지에 대한 정보를 저장할 객체 생성
var meetingDay = new Object();
// 오늘 날짜를 id가 today인 단락에 출력
// toLocaleDateString() 메소드를 사용하여 지역 날짜 포맷으로 날짜를 출력 
// 요일은 toWeekDay() 함수를 이용하여 문자열로 반환
document.getElementById('today').innerHTML = "오늘은 " + today.toLocaleDateString() + " " + toWeekDay(today.getDay()) + " 입니다.";
// name이 count_btn인 단추를 클릭하면 todayCounter 함수 콜백
document.getElementById('count_btn').addEventListener('click', todayCounter, false);
// name이 memorial_btn인 단추를 클릭하면 dayCounter 함수 콜백
document.getElementById('memorial_btn').addEventListener('click', dayCounter, false);
// 오늘이 아기 출생일로 부터 몇일 째인가를 구하는 함수
function todayCounter() {
setupBirthday();
// 오늘날짜에 생일 날짜를 뺀다. 날짜의 연산은 밀리초로 결과나 반환된다.
var days = today - meetingDay.date;
// 밀리초로 반환된 값을 날짜로 변환하여 출력
// 값 올림 메소드인 ceil을 적용한 이유는 결과가 12.34 이며 12일과 그 다음날을 살고 있는 것이므로 소수점 이하자리는 올린다..
countDayOutput.value = Math.ceil(days/1000/60/60/24);
}
function dayCounter() {
// 사용자가 입력한 기념일 날짜를 가져온다. 예) 100일
var memorialDay = document.getElementById('memorial_day').value;
// 만일 날짜 객체가 생성되지 않았다면 사용자의 입력 내용으로 날짜 객체를 생성한다.
if (!meetingDay.setted) setupBirthday();
// 계산된 결과 값을 넣을 날짜 객체 생성
var targetDay = new Date();
var theDay = meetingDay.date.getDate();
targetDay.setTime(meetingDay.date.getTime());
targetDay.setDate(theDay + Number(memorialDay) - 1);

memorialCountOutput.value = memorialDay;
// 날짜 객체에 toLocaleDateString()을 적용하면 지역포맷 날짜 문자열로 반환된다.
memorialDayOutput.value = targetDay.toLocaleDateString() + " " + toWeekDay(targetDay.getDay());
}
function setupBirthday() {
// 사용자가 입력한 폼의 값을 변수에 지정
var year = document.getElementById('meeting_year').value;
var month = document.getElementById('meeting_month').value;
var day = document.getElementById('meeting_day').value;
// date 프로퍼티에 날짜 객체를 생성하여 넣는다.
meetingDay.date = new Date(year, month, day);
// 날짜 객체가 생성되었는지를 표시하는 부울 프로퍼티
meetingDay.setted = true;
}
// 날짜 객체의 요일 숫자 코드를 받아서 한글로 반환하는 함수
function toWeekDay(dayNumber) {
   var array = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"];
   return array[dayNumber];
}
}

style.css
body {
font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif;
font-size: 0.8em;
}

#wrapper {
width: 400px;
border: 1px solid gray;
margin:auto;
}

p {
text-align: center;
}

h1 {
color: #ffb700;
font-size: 1.8em;
text-align: center;
}

input {
text-align: right;
}

#meeting_year {
width: 50px;
}

#meeting_day {
width: 30px;
}

#today_count {
width: 80px;
}

#memorial_day {
width: 80px;
}

#memorial_count {
width: 40px;
}

#memorial_date {
width: 130px;
}

hr {
border: 0px solid white;
border-top: 1px dashed gray;
width: 300px;
}


1차원 배열 출력

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>literal Demo </title>

    </head>

    <body>

        <script>

            var array = [1,2,3,4,5];

            document.write("<p style='font-size:30pt'>");

            for(var i = 0 ; i < array.length; i++){

                document.write(array[i] + "&nbsp;");

            }

            document.write("</p>");

        </script>

    </body>

</html>

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

2차원 배열 출력 1

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Initializer Expressions </title>

    </head>

    <body>

        <script>

            var clouds = ["cumulus", "nimbus", "cirrus"];

            var str="";

            for(var i = 0; i<clouds.length; i++){

                str+="I wandered lonely as a " + clouds[i] + "\n";

            }

            alert(str);

            

            document.write("<table>");

            document.write("<tr>");

            document.write("<th>No.</th><th>Name</th><th>Age</th>");

            document.write("</tr>");

            var cards = [[1,"Michael",30],[2,"Sujan",25],[3,"Sally",45]];

            for(var i = 0 ; i < cards.length; i++){

                document.write("<tr>");

                for(var j = 0 ; j < cards[i].length ; j++){

                    document.write("<td>" + cards[i][j] + "</td>");

                }

                document.write("</tr>");

            }

            document.write("</table>");

        </script>

    </body>

</html>

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

2차원 배열 출력 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Array Initializer Expressions </title>

    </head>

    <body>

        <script>

            var clouds = ["cumulus", "nimbus", "cirrus"];

            var str="";

            for(var i = 0; i<clouds.length; i++){

                str+="I wandered lonely as a " + clouds[i] + "\n";

            }

            alert(str);

            

            document.write("<table>");

            document.write("<tr>");

            document.write("<th>No.</th><th>Name</th><th>Age</th>");

            document.write("</tr>");

            var cards = [[1,"Michael",30],[2,"Sujan",25],[3,"Sally",45]];

            for(var i = 0 ; i < cards.length; i++){

                document.write("<tr>");

                for(var j = 0 ; j < cards[i].length ; j++){

                    document.write("<td>" + cards[i][j] + "</td>");

                }

                document.write("</tr>");

            }

            document.write("</table>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

값 접근

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>literal Demo </title>

    </head>

    <body>

        <script>

            var obj = {hakbun:1101, irum:"한송이", kor:90, eng:80, mat:100};

            obj.sum = obj.kor + obj.eng + obj.mat;

            obj.avg = obj.sum / 3.;

            document.write("<h2>Sungjuk</h2>");

            document.write("<ol>");

            document.write("<li>학번 : " + obj.hakbun);

            document.write("<li>이름 : " + obj["irum"]);

            document.write("<li>국어 : " + obj["kor"]);

            document.write("<li>영어 : " + obj["eng"]);

            document.write("<li>수학 : " + obj["mat"]);

            document.write("<li>총점 : " + obj.sum);

            document.write("<li>평균 : " + obj.avg);

            document.write("</ol>");

        </script>

    </body>

</html>

// .으로 접근하든지 []로 접근하든지 모두 가능.

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

associative array 값 접근 2

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>literal Demo </title>

    </head>

    <body>

        <script>

            var employee = {empno:7788, ename:"Scott", 

                                     hiredate : new Date(),    //현재날짜 및 시간 찍힘

                                     hobby : ["음악감상", "독서", "농구"],

                                     mycar : "Sonata"};

            document.write("사번 :  " + employee.empno + "<br>");

            document.write("이름 :  " + employee["ename"] + "<br>");

            document.write("입사날짜 :  " + employee.hiredate + "<br>");

            document.write("취미 :  ");

            for(var i = 0 ; i < employee.hobby.length ; i++){

                document.write(employee.hobby[i] + ", ");

            }                   

        </script>

    </body>

</html>

출력:

사번 : 7788

이름 : Scott

입사날짜 : Wed May 28 2014 11:08:16 GMT+0900 (Korea Standard Time)

취미 : 음악감상, 독서, 농구,

//따라서 .은 [''] 나 [""] 와 같다. 

따라서 다음 세가지는 같다.

picture.details.type

picture.details['type']

picture['details']['type'] 

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

Function literal 

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>literal Demo </title>

    </head>

    <body>

        <script>

            var aaa = function(a, b){  //aaa는 함수의 주소를 가지고 있다고 생각하면 됨.

                              return a + b;  

                           };

            document.write(aaa(5, 9));

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

delete : 멤버를 없애는 연산자.(내가만든건 없앨 수 있고 미리만들어진 것은 없앨 수 없음. 지워도 공간은 남음)

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> delete Operators </title>

    </head>

    <body>

        <script>

            var o = {x:1, y:2};

            document.write("<p>delete o.x = " + (delete o.x) + "</p>");

            document.write("<p>\"x\" in o = " + ("x" in o) +"</p>");

            

            var a=[1,2,3];

            document.write("<p>delete a[2] = " +(delete a[2]) + "<p>");   /* 값만 지우고 공간은 지우지 않음 */

            document.write("<p>a.length = " + a.length + "<p>");  

            for(var i = 0; i < a.length ; i++){

                document.write(i+"="+a[i]+"<br>");

            }

        </script>


    </body>

</html>

출력:

delete o.x = true


"x" in o = false


delete a[2] = true


a.length = 3


0=1

1=2

2=undefined

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

in  : (데이터가 아닌) 멤버가 있으면 true 없으면 false. 숫자일때는 

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

    </head>


    <body>

            <script>

            var point ={x:1,y:1};

            document.write("<p>\"x\" in point = "+ ("x" in point)+"</p>"); //멤버 "x"가 있으므로 true

            document.write("<p>\"z\" in point = "+ ("z" in point)+"</p>");

            document.write("<p>\"toString\" in point = "+ ("toString" in point)+"</p>");  //toString은 point의 멤버이므로 true

            

            var data=[7,8,9]; //숫자는 index로 해서, index까지 있으면 true

            document.write("<p>\"0\" in data = "+ ("0" in data)+"</p>");  //"0"=0으로 생각해서 0번째 index가 있으므로 true

            document.write("<p>1 in data = "+ (1 in data)+"</p>");

            document.write("<p>3 in data = "+ (3 in data)+"</p>");  //index가 2번째까지밖에 없으므로 false

        </script>

    </body>

</html>

출력:

"x" in point = true


"z" in point = false


"toString" in point = true


"0" in data = true


1 in data = true


3 in data = false

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적관리 프로그램

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 성적관리프로그램 </title>

        <script src="js/student.js"></script>

        <script>

            window.addEventListener("load", init, false);

            function init(){

                document.getElementById('btnInput').addEventListener("click", click, false);

            }

            function click(){

                var chulsu = new Student(

                                    document.getElementById('hakbun').value,

                                    document.getElementById('irum').value,

                                    parseInt(document.getElementById('kor').value),

                                    parseInt(document.getElementById('eng').value),

                                    parseInt(document.getElementById('mat').value)

                );

                calc(chulsu);

                output(chulsu);

            }

            function output(s){

                var str = "학번 : " + s.getHakbun() + "\n" +

                              "이름 : " + s.getIrum() + "\n" + 

                              "국어 : " + s.getKor() + "\n" + 

                              "영어 : " + s.getEng() + "\n" +

                              "수학 : " + s.getMat() + "\n" +

                              "총점 : " + s.getSum()+ "\n" +

                              "평균 : " + s.getAvg() + "\n" +

                              "학점 : " + s.getGrade();

                alert(str);                              

            } 

            function calc(s){

                var sum = s.getKor() + s.getEng() + s.getMat();

                var avg = sum / 3.;

                s.setSum(sum);

                s.setAvg(avg);

                var grade = getGrade(avg);

                s.setGrade(grade);

            }

            function getGrade(avg){

                var grade = 'F';

                switch(parseInt(avg / 10)){

                    case 10:

                    case 9 :  grade = 'A'; break;

                    case 8 :  grade = 'B'; break;

                    case 7 :  grade = 'C'; break;

                    case 6 :  grade = 'D'; break;

                    default :  grade = 'F';

                }

                return grade;

            }

        </script>

        <link rel="stylesheet" href="css/style.css">

    </head>

    <body>

        <h1>성적관리프로그램</h1>

        <table>

            <form>

                <tr><th><label for="hakbun">학번</label></th>

                        <td><input type="text" id="hakbun" autofocus></td>                    

                </tr>

                <tr><th><label for="irum">이름</label></th>

                        <td><input type="text" id="irum"></td>                    

                </tr>

                <tr><th><label for="kor">국어</label></th>

                        <td><input type="text" id="kor"></td>                    

                </tr>

                <tr><th><label for="eng">영어</label></th>

                        <td><input type="text" id="eng"></td>                    

                </tr>

                <tr><th><label for="mat">수학</label></th>

                        <td><input type="text" id="mat"></td>                    

                </tr>

                <tr><td colspan="2"><input type="button" id="btnInput" value="입력하기">

                       <input type="reset" value="다시하기"></td>

                </tr>

            

            </form>

        </table>

    </body>

</html>


student.js

var Student = function(hakbun, irum, kor, eng, mat){

    var hakbun = hakbun;

    var irum = irum;

    var kor = kor;

    var eng = eng;

    var mat = mat;

    var sum;

    var avg;

    var grade;

    

    this.getHakbun = function() { return hakbun; };

    this.getIrum = function() { return irum; };

    this.getKor = function() { return kor; };

    this.getEng = function() { return eng; };

    this.getMat = function() { return mat; };

    this.getSum = function() { return sum; };

    this.getAvg = function() { return avg; };

    this.setSum = function(total){ sum = total; };

    this.setAvg = function(average){ avg = average; };

    this.getGrade = function(){ return grade;};

    this.setGrade = function(hakjum) { grade = hakjum; };

};



style.css

* {

    margin:0;

    padding:0;

}

body{

   font-size:1.5em;

}

h1{

    text-align:center;

    margin-top:30px;

    margin-bottom:20px;

}

table{

    margin-left:auto;

    margin-right:auto;

    border-collapse: collapse;

    border:3px solid orange;

    padding:5px;

}

th,td{

    padding:5px;

    border:0px solid black;

}

th{

    background-color:yellow;

    width:100px;

}

input[type="text"]{

    font-size:1.5em;

    width:300px;

}

input[type="button"], input[type="reset"]{

    font-size:1.5em;

    width:150px;

    background-color: maroon;

}

tr:last-child > td {

    text-align:center;

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

practice 계절

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> Switch Statement Demo </title>

    </head>

    <body>

        <script>

            var season = prompt("당신은 어느 계절을 좋아하시나요?(spring | summer | fall | winter)");

            switch(season){

                case "spring" :  alert("개나리, 진달래");  break;

                case "summer" : alert("장미, 아카시아"); break;

                case "fall" :   alert("백합, 코스모스");  break;

                case "winter" :    alert("동백, 매화");

            }

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

소수 구하기

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 소수 구하기 </title>

    </head>

    <body>

        <script>

            for(var i = 2 ; i < 51 ; i++){

                if(isPrime(i)){

                    document.write(i + ", ");

                }

            }

            function isPrime(number){

                var aaa = true;

                for(var i = 2 ; i < number ; i++){

                    if(number % i == 0) {

                        aaa = false;

                        break;

                    } 

                }

                return aaa;

            }

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

구구단

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 구구단 </title>

        <style>

            table{

                border-collapse: collapse;

                margin:auto;

                width:800px;

            }

            th{

                border:2px solid white;

                font-size:1.5em;

                background-color: blue;

                color:white;

                height:50px;

            }

            td{

                border:2px solid orange;

                font-size:0.8em;

                height:180px;

                text-align:center;

            }

        </style>

    </head>

    <body>

        <h1>구구단</h1>

        <script>

            document.write("<table>");

            document.write("<thead>");

            document.write("<tr>");

            for(var i = 2 ; i < 10 ; i++){

                document.write("<th>" + i + "단</th>");

            }

            document.write("</tr>");

            document.write("<thead>");

            document.write("<tbody>");

            document.write("<tr>");

            

            for(var j = 2 ; j < 10 ; j++){

                document.write("<td>");

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

                    document.write(j + " x " + k + " = " + k * j + "<br>");                  

                }

                document.write("</td>");

            }

            

            document.write("</tr>");

            document.write("</tbody>");

            document.write("</table>");

        </script>

    </body>

</html>

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

성적프로그램 : 여러명 입력 가능하게해서

sungjukmgmt.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 성적관리프로그램 </title>

        <script src="js/student.js"></script>

        <script src="js/input.js"></script>

        <script src="js/calc.js"></script>

        <script src="js/sort.js"></script>

        <script src="js/output.js"></script>

        <script>

            window.addEventListener("load", init, false);

            var array = new Array(); 

            function init(){

                document.getElementById("btnInput").disabled = false;

                document.getElementById("btnCalc").disabled = true;

                document.getElementById("btnSort").disabled = true;

                document.getElementById("btnOutput").disabled = true;

                document.getElementById('btnInput').addEventListener("click", input, false);

                document.getElementById('btnCalc').addEventListener("click", calc, false);

                document.getElementById('btnSort').addEventListener("click", sort, false);

                document.getElementById('btnOutput').addEventListener("click", output, false);

            }           

        </script>

        <link rel="stylesheet" href="css/style.css">

    </head>

    <body>

        <h1>성적관리프로그램</h1>

        <table>

            <form>

                <tr><th><label for="hakbun">학번</label></th>

                        <td><input type="text" id="hakbun" autofocus></td>                    

                </tr>

                <tr><th><label for="irum">이름</label></th>

                        <td><input type="text" id="irum"></td>                    

                </tr>

                <tr><th><label for="kor">국어</label></th>

                        <td><input type="text" id="kor"></td>                    

                </tr>

                <tr><th><label for="eng">영어</label></th>

                        <td><input type="text" id="eng"></td>                    

                </tr>

                <tr><th><label for="mat">수학</label></th>

                        <td><input type="text" id="mat"></td>                    

                </tr>

                <tr><td colspan="2"><input type="button" id="btnInput" value="입력하기">

                       <input type="button" id="btnCalc" value="계산하기">

                       <input type="button" id="btnSort" value="정렬하기">

                       <input type="button" id="btnOutput" value="출력하기">

                       </td>

                </tr>            

            </form>

        </table>

        <hr>

        <div id="result"></div>

    </body>

</html>


student.js

var Student = function(hakbun, irum, kor, eng, mat){

    var hakbun = hakbun;

    var irum = irum;

    var kor = kor;

    var eng = eng;

    var mat = mat;

    var sum;

    var avg;

    var grade;

    

    this.getHakbun = function() { return hakbun; };

    this.getIrum = function() { return irum; };

    this.getKor = function() { return kor; };

    this.getEng = function() { return eng; };

    this.getMat = function() { return mat; };

    this.getSum = function() { return sum; };

    this.getAvg = function() { return avg; };

    this.setSum = function(total){ sum = total; };

    this.setAvg = function(average){ avg = average; };

    this.getGrade = function(){ return grade;};

    this.setGrade = function(hakjum) { grade = hakjum; };

};


input.js

function input(){

    var chulsu = new Student(

                        document.getElementById('hakbun').value,

                        document.getElementById('irum').value,

                        parseInt(document.getElementById('kor').value),

                        parseInt(document.getElementById('eng').value),

                        parseInt(document.getElementById('mat').value)

    );

    array.push(chulsu);

    document.getElementById("hakbun").value = "";

    document.getElementById("irum").value = "";

    document.getElementById("kor").value = "";

    document.getElementById("eng").value = "";

    document.getElementById("mat").value = "";

    alert("잘 입력됐습니다.");

    document.getElementById("btnCalc").disabled = false;

    document.getElementById("btnOutput").disabled = false;

}


calc.js

function calc(){

    for(var i = 0 ; i < array.length ; i++){

        var sum = array[i].getKor() + array[i].getEng() + array[i].getMat();

        var avg = sum / 3.;

        array[i].setSum(sum);

        array[i].setAvg(avg);

        var grade = getGrade(avg);

        array[i].setGrade(grade);

    }

}

function getGrade(avg){

    var grade = 'F';

    switch(parseInt(avg / 10)){

        case 10:

        case 9 :  grade = 'A'; break;

        case 8 :  grade = 'B'; break;

        case 7 :  grade = 'C'; break;

        case 6 :  grade = 'D'; break;

        default :  grade = 'F';

    }

    return grade;

}


sort.js

function sort(){

    for(var i=0; i < array.length; i++){

        for(var j=0; j<array.length-1-i; j++){

            if(array[j].getSum()<array[j+1].getSum()){

                var temp = array[j];

                array[j]=array[j+1];

                array[j+1]=temp;

            }

        }

    }


output.js

function output(){

    var str = "<table align='center' border='1' cellspaciing='0'><thead><tr><th>학번</th><th>이름</th>" +

                  "<th>국어</th><th>영어</th><th>수학</th><th>총점" +

                  "</th><th>평균</th><th>학점</th></tr></thead><tbody>";

    for(var i = 0 ; i < array.length ; i++){

        str += "<tr>";

        str += "<td>" + array[i].getHakbun() + "</td>";

        str += "<td>" + array[i].getIrum() + "</td>";

        str += "<td>" + array[i].getKor() + "</td>";

        str += "<td>" + array[i].getEng() + "</td>";

        str += "<td>" + array[i].getMat() + "</td>";

        str += "<td>" + array[i].getSum() + "</td>";

        str += "<td>" + array[i].getAvg() + "</td>";

        str += "<td>" + array[i].getGrade() + "</td>";

        str += "</tr>";

    }                      

    str += "</tbody></table>";

    document.getElementById("result").innerHTML = str;               

}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

환자 관리 프로그램

index.html

<!DOCTYPE html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title> 환자관리프로그램 </title>

        <script src="js/patient.js"></script>

        <script src="js/input.js"></script>

        <script src="js/calc.js"></script>

        <script src="js/sort.js"></script>

        <script src="js/output.js"></script>

        <script>

            window.addEventListener("load", init, false);

            var array = new Array(); 

            function init(){

                document.getElementById("btnInput").disabled = false;

                document.getElementById("btnCalc").disabled = true;

                document.getElementById("btnSort").disabled = true;

                document.getElementById("btnOutput").disabled = true;

                document.getElementById('btnInput').addEventListener("click", input, false);

                document.getElementById('btnCalc').addEventListener("click", calc, false);

                document.getElementById('btnSort').addEventListener("click", sort, false);

                document.getElementById('btnOutput').addEventListener("click", output, false);

            }           

        </script>

        <link rel="stylesheet" href="css/style.css">

    </head>

    <body>

        <fieldset>

        <table>

                <legend>환자데이터입력</legend>

            <form>

                <tr><th><label for="hakbun">번호</label></th>

                        <td><input type="text" id="bunho" autofocus></td>                    

                </tr>

                <tr><th><label for="irum">진료코드</label></th>

                        <td><input type="text" id="code"></td>                    

                </tr>

                <tr><th><label for="kor">입원일수</label></th>

                        <td><input type="text" id="days"></td>                    

                </tr>

                <tr><th><label for="eng">나이</label></th>

                        <td><input type="text" id="age"></td>                    

                </tr>

                <tr><td colspan="2"><input type="button" id="btnInput" value="입력하기">

                       <input type="button" id="btnCalc" value="계산하기">

                       <input type="button" id="btnSort" value="정렬하기">

                       <input type="button" id="btnOutput" value="출력하기">

                       </td>

                </tr>            

            </form>           

        </table>

        </fieldset>

        <br><br>

        

        <div id="result"></div>

    </body>

</html>


patient.js

/**

 * @author Instructor

 */

var Patient = function(bunho, code, days, age){

    var bunho = bunho;

    var code = code;

    var days = days;

    var age = age;

    var 진찰부서;

    var 진찰비;

    var 입원비;

    var 진료비;

    

    this.getBunho = function() { return bunho; };

    this.getCode = function() { return code; };

    this.getDays = function() { return days; };

    this.getAge = function() { return age; };

    this.get진찰부서 = function() { return 진찰부서; };

    this.get진찰비 = function() { return 진찰비; };

    this.get입원비 = function() { return 입원비; };

    this.get진료비 = function() { return 진료비; };

    this.set진찰부서 = function(department){ 진찰부서 = department; };

    this.set진찰비 = function(fee){ 진찰비 = fee; };

    this.set입원비 = function(done){ 입원비 = done;};

    this.set진료비 = function(money) { 진료비 = money; };

};


input.js

/**

 * @author Instructor

 */

function input(){

    var chulsu = new Patient(

                        document.getElementById('bunho').value,

                        document.getElementById('code').value,

                        parseInt(document.getElementById('days').value),

                        parseInt(document.getElementById('age').value)                        

    );

    array.push(chulsu);

    document.getElementById("bunho").value = "";

    document.getElementById("code").value = "";

    document.getElementById("days").value = "";

    document.getElementById("age").value = "";

    alert("잘 입력됐습니다.");

    document.getElementById("btnCalc").disabled = false;

    document.getElementById("btnSort").disabled = false;

    document.getElementById("btnOutput").disabled = false;

}

calc.js

/**

 * @author Instructor

 */

function calc(){

    for(var i = 0 ; i < array.length ; i++){

        var dayone = (array[i].getDays() <= 3) ? 30000 : 25000;  //1일 입원비

        var totalfee = dayone * array[i].getDays();  //총입원비

        var fee =  totalfee * getRate(array[i].getDays());  //입원비

        var money = getFee(array[i].getAge()) + fee;  //진료비

        var department = getDepartment(array[i].getCode());  //진찰부서

        array[i].set진찰부서(department);

        array[i].set진찰비(getFee(array[i].getAge()));  

        array[i].set입원비(parseInt(fee));

        array[i].set진료비(parseInt(money));

    }

}

function getDepartment(code){

    var department;

    switch(code){

        case "MI": department = "외과"; break;

        case "NI" :  department = "내과"; break;

        case "SI" :  department = "피부과"; break;

        case "TI" :  department = "소아과"; break;

        case "VI" :  department = "산부인과"; break;

        case "WI" :  department = "비뇨기과"; break;

    }

    return department;

}

function getFee(age){

    var fee;

    if(age < 10) fee = 7000;

    else if(age >= 10 && age < 20) fee = 5000;

    else if(age >= 20 && age < 30) fee = 8000;

    else if(age >= 30 && age < 40) fee = 7000;

    else if(age >= 40 && age < 50) fee = 4500;

    else fee = 2300;

    return fee;

}

function getRate(days){

    var rate;

    if(days < 10) rate = 1.0;

    else if(days >= 10 && days < 15) rate = 0.85;

    else if(days >= 15 && days < 20) rate = 0.8;

    else if(days >= 20 && days < 30) rate = 0.77;

    else if(days >= 30 && days < 100) rate = 0.72;

    else rate = 0.68;

    return rate;

}


sort.js

/**

 * @author Instructor

 */

function sort(){

    for(var i = 0 ; i < array.length - 1 ; i++){

        for(var j = 0 ; j < array.length - 1 - i ; j++){

            if(array[j].get진료비() < array[j+1].get진료비())

                swap(j, j+1);

        }

    }

}

function swap(a, b){

    var temp = array[a];

    array[a] = array[b];

    array[b] = temp;

}


output.js

/**

 * @author Instructor

 */

function output(){

    var str = "<table><caption>&lt;&lt;병원관리프로그램&gt;&gt;</caption><thead><tr><th>번호</th><th>진찰부서</th>" +

                  "<th>진찰비</th><th>입원비</th><th>진료비</th></tr></thead><tbody>";

    for(var i = 0 ; i < array.length ; i++){

        str += "<tr>";

        str += "<td>" + array[i].getBunho() + "</td>";

        str += "<td>" + array[i].get진찰부서() + "</td>";

        str += "<td>" + array[i].get진찰비() + "</td>";

        str += "<td>" + array[i].get입원비() + "</td>";

        str += "<td>" + array[i].get진료비() + "</td>";

        str += "</tr>";

    }                      

    str += "</tbody></table>";

    document.getElementById("result").innerHTML = str;               

}


style.css

* {

    margin:0;

    padding:0;

}

body{

   font-size:1.5em;

}

fieldset{

    margin-top:30px;

    margin-left:auto;

    margin-right:auto;

    padding:30px;

    width:450px;

}

form > table{

    margin:auto;

    border-collapse: collapse;

    border:3px solid orange;

    padding:10px;

}

form th,td{

    padding:5px;

    border:0px solid black;

}

form th{

    background-color:yellow;

    width:100px;

}

input[type="text"]{

    font-size:1.5em;

    width:300px;

}

input[type="button"]{

    font-size:0.9em;

    width:100px;

}

tr:last-child > td {

    text-align:center;

}

div table{

    margin:auto;

    border-collapse: collapse;

    border:3px solid green;

    padding:10px;

    width:500px;

    font-size:0.8em;

}

div table th,td{

    padding:5px;

    border:0px solid black;

    text-align:center;

}

div table th{

    background-color:lightblue;

    width:100px;

}







+ Recent posts