select * from student where name like '%순%';

- 이름에 순이 들어가는 컬럼 찾을 때


[name과 id 차이]

<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Insert title here</title>

    <script>

        function fn() {

            xmlHttp=new XMLHttpRequest();//ajax

            xmlHttp.onreadystatechange=on_ready;

            s=`DBInsert.jsp?myname=${idname.value}&myage=${idage.value}`;

            xmlHttp.open("GET", s);

            xmlHttp.send();//submit

        }

        function on_ready() {

            if(xmlHttp.readyState==4 && xmlHttp.status==200){

                mydiv.innerHTML=xmlHttp.responseText;

            }

        }

    </script>

</head>

<body>

<div id="mydiv">표시</div>

이름 : <input id="idname" type="text" name="myname"><br>

나이 : <input id="idage" type="text" name="myage"><br>

<button onclick="fn()">button</button>

</body>

</html>


myname=${idname.value}&myage=${idage.value}`;

name은 파라미터 값 넘길 때 쓰는 키값

- ajax 사용해서 값 넘길 때

(id)=${id.value}&${id.value}

(name)=${id.value}&${id.value}

- form으로 값 넘길때

name을 사용해서 넘긴다.

XML, JSON, 문자열



cross domain 정책 : html에서 다른 서버의 html 읽을 수 없다.

[웹어플리케이션 아키텍쳐]

· Web Client

     (HTTP request / HTTP response)

· Web Server

· DB Server


[웹 프로토콜 - 통신절차]

· TCP(HTTP)는 3가지 절차를 통해 통신이 이루어진다.

(1) 세션 연결 ( 나는 너와 통신하고 싶다. )

(2) 데이터 송.수신 ( 웹 브라우저에 페이지 로딩 )

(3) 세션 종료 ( 통신 종료 )


<form method="get" action="test.jsp"> </form>

- method default : get(2,083 정도의 길이 데이터만을 처리한다.)


[HTTP Request]

· GET방식

URL 뒤에 이어서 문자열로 서버에 전달을 한다.

URL 뒤에 "?" 마크를 통해 URL의 끝을 알리면서, 데이터 표현의 시작점을 알린다. 

URL에 정보가 그대로 노출되어 보안상 취약하다.

간단한 데이터를 넣도록 설계되어서 전송할 데이터의 제한이 있다.


· POST방식

URL 뒤에 붙여서 보내지 않고 HTTP 바디에 데이터를 넣어서 보낸다.

정보를 드러내지 않아 GET방식 보다 보안에 유리하다.

전송할 데이터의 제한이 없다.


[HTTP Response]

· HTTP Status Code(응답코드) 종류

- 200번 : 요청성공

- 201번 : 원격지서버에 파일 생성

302번 : 페이지이동

- 304번 : 로컬 캐쉬정보이용

- 401번 : 인증실패

- 403번 : 접근금지

- 404번 : 페이지없음

- 500번 : 서버에러


//post 요청인 경우 header 들어가는 스트링

xmlHttp.setRequestHeader('Content-Type', "application/x-www-form-urlencoded;charset=utf-8");

- 설정 안해주면 한글 깨져서 null값이 출력된다.



<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

    

<%@ page import="java.sql.*" %>

<%

try{

Class.forName("org.gjt.mm.mysql.Driver");

out.print("driver load success"+"<br>");

}catch(Exception ex){

out.print("driver load fail"+"<br>");

}

String mysqlURL="jdbc:mysql://localhost:3306/test";

//sql database가 있는 url과 접속할 database명

String sID="root";

String sPass="1234";

String sql="insert into student(name, age) values ('홍길동', 30)";

Connection conn=null;

Statement stmt=null;

try{

conn=DriverManager.getConnection(mysqlURL, sID, sPass);

stmt=conn.createStatement();

stmt.execute(sql);

conn.close();

out.print("<h1>추가성공</h1>");

}catch(Exception ex){

out.print("<h1>추가실패</h1>");

}finally{

conn.close();

}

%> 


'SK고용디딤돌' 카테고리의 다른 글

직무교육 13일차(HTML5 API)  (0) 2017.07.26
직무교육 12일차(DB연동)  (1) 2017.07.25
직무교육 10일차(JavaScript)  (0) 2017.07.21
직무교육 9일차(JavaScript)  (0) 2017.07.20
직무교육 8일차(JavaScript)  (0) 2017.07.19

       s = encodeURIComponent(s);//특수기호 포함 encode

        s = encodeURI(s);

        document.write(s+'<br><br>');

        s=decodeURI(s);//한글만 decode

        s=decodeURIComponent(s); //특수기호 포함 decode


[mysql Download]

Community Download -> Download MySQL Community Server -> installer 클릭 -> 378.8M 다운로드 -> No, thanks


[이벤트 처리]

· 버튼 클릭 -> 이벤트 발생 -> 함수 실행 -> 페이지 변화(2,3,4 권장)

1) 버튼에 이벤트 속성 주기 -> onclick="fn()";

2) 버튼에 아이디(mybtn) 부여 -> mybtn.onclick=function();//랜더링완료이후(body onload / window.onload / window.addEventListner("load", 콜백함수)

3) window.onload=function () {

            mybtn.addEventListener("click", fn)//(string, callback함수)

    }

4) window.addEventListener("load", init);

        function init() {

            mybtn.addEventListener("click", fn)//(string, callback함수)

        }

5) window.addEventListener("load", function () {

            mybtn.addEventListener("click", function () {

                alert('call~~~~~~~');

            })

        })

· onfocus="foFn()"; : 해당 영역에 커서 위치할 때

· onblur="bluFn()"; : 해당 영역에서 커서가 빶져나갔을 때

· <script>

        function fn() {

            alert('call');

            location.href="a.html";

        }

    </script>

<form action="javascript:fn()"> : 자바스크립트 함수 호출 가능

· onkeypress="fn()" : 아스키코드(a-z 0-9 !@#%^^)

·  onkeyup="fn()" : 키 눌렀다가 땔때

·  onkeydown="fn()" : 키 누를 때

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        function fn(event) {

            console.log('call', event.which);//누르는 키 값 알려준다.

        }

    </script>

</head>

<body>

    <input id="txt1" type="text" onkeydown="fn(event)"><br>

</body>

</html> 



[키보드로 움직이기]

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

        #mydiv{

            position: absolute;

            left: 100px;

            width:50px;

            height:50px;

            background-color: red;

        }

    </style>

    <script>

        n=100;

        function fn(event) {

            if(event.which==39){

                n+=10;

            }else if(event.which==37){

                n-=10;

            }

            mydiv.style.left=n+"px";          

        }

    </script>

</head>

<body>

    <div id="mydiv" tabindex="0" onkeydown="fn(event)"></div>

</body>

</html> 


· rst=eval("10+20");

  console.log(rst);//출력결과 30나옴

· 

· set SQL_SAFE_UPDATES=0;

-mysql 처음 실행 시, 삭제 안될때 작성

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

· 

[DOM 다루기]



· tt.innerHTML="<h1>대한민국</h1>";

- innerText말고 innerHTML을 사용하면 태그를 사용할 수 있다.


 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>


    <script>

        function fn() {

           tt = document.getElementById('test1');//getElements -> array

           tt.innerHTML="<h1>대한민국</h1>";


           ctest=document.getElementsByClassName('test2');

           ctest[0].innerText="헬로";


           for(n=0; n<ctest.length; n++)

           {

               ctest[n].innerText="헬로";

           }

           mydiv=document.getElementsByTagName('div')//태그명이 div인 array

            for(n=0; n<mydiv.length; n++)

            {

                mydiv[n].innerText="헬로";

            }


           myli=document.getElementsByTagName('li');//태그명이 li인 array

           myli=Array.from(myli);//for in문 사용하기 위해서 array로 변경

           for(n in myli){

               myli[n].innerText="hello"

           }


           myin=document.getElementsByName('myname');//name속성이 myname인 것

            myin[0].style.backgroundColor="yellow";

            myin[1].style.backgroundColor="blue";

        }

    </script>


</head>

<body>


    <div id="test1">테스트1</div>

    <div class="test2">테스트2</div>

    <div class="test2">테스트3</div>


    <input type="text" name="myname"><br>

    <input type="text" name="myname"><br>

    <input type="number" name="myage"><br>


    <ul>

        <li>사과</li>

        <li>딸기</li>

        <li>포도</li>

    </ul>


    <button onclick="fn()">확인</button>

</body>

</html>


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>



        img{

            width:300px;

            height:300px;

        }

    </style>


    <script>


        function fn() {

            /*aa=document.querySelector('#test1');

            //css의 selecor과 동일. 하나만 return

            aa.innerText="hello";*/


            /*bb = document.querySelector('.test2');//여러개일 경우 첫번재 하나만 return

            bb.innerText="hello1";*/


            /*cc = document.querySelectorAll('div');//all은 array로 return

            for(d in cc)

            {

                cc[d].innerText="hello2";

            }*/

            /*cc[0].innerText="hello2";

            cc[2].innerText="hello2";//for문 돌려서 하기*/


            /*dd = document.querySelectorAll('[name="myname"]');//name속성이 myname인 것

            dd = Array.from(dd);//HTMLCollection을 array로 변환

            dd.forEach(function (v, i) {

                v.style.backgroundColor="yellow";

            })*/


            /*ee = document.querySelectorAll('#fruit li');//id fruit이고 li인 것

            ee = Array.from(ee);//HTMLCollection을 array로 변환

            ee.forEach(function (v, i) {

                v.style.backgroundColor="yellow";

            })*/


            /*ff = document.querySelectorAll('img');//image인 것

            //ff = document.querySelectorAll('[src*="image"]');

            ff = Array.from(ff);//HTMLCollection을 array로 변환

            ff.forEach(function (v, i) {

                v.style.border= "5px dashed blue";

            })*/


            gg = document.querySelectorAll('#fruit li:nth-child(2n)');

            //id fruit이고 li에서 2의 배수인 것

            gg = Array.from(gg);//HTMLCollection을 array로 변환

            for(d in gg)

            {

                gg[d].innerText="과일";

                gg[d].style.backgroundColor="skyblue";

            }

        }

    </script>

</head>

<body>


    <img src="image/a.png">&nbsp;&nbsp;

    <img src="image/b.png"><br>


    <div id="test1">테스트1</div>

    <div class="test2">테스트2</div>

    <div class="test2">테스트3</div>


    <input type="text" name="myname"><br>

    <input type="text" name="myname"><br>

    <input type="number" name="myage"><br>


    <ul id="fruit">

        <li>사과</li>

        <li>딸기</li>

        <li>포도</li>

        <li>사과</li>

        <li>딸기</li>

        <li>포도</li>

    </ul>


    <ul>

        <li>사과1</li>

        <li>딸기1</li>

        <li>포도1</li>

    </ul>


    <button onclick="fn()">확인</button>


</body>

</html> 


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        function fn() {

            /*//radio

            selGrade = document.querySelector('[name="grade"]:checked');

            mydiv.innerText=selGrade.value;*/


            /*std = document.querySelector('[type="checkbox"]');

            //std.checked = true;//checkbox에 체크가 된다.

            if(std.checked == true){//checkbox에 체크되어있을 경우

                mydiv.innerText="학생";

            }else{//checkbox에 체크가 안되어있을 경우

                mydiv.innerText="학생아님";

            }*/


            /*txt = document.querySelector('[type="text"]');

            mydiv.innerText=txt.value;//input에 작성에 text가 출력됨*/


            /*chkHobby = document.querySelectorAll('[name="hobby"]:checked');

            chkHobby=Array.from(chkHobby);

            mydiv.innerText="";

            chkHobby.forEach(function (v, i) {

                mydiv.innerText += v.value;

            })//checkbox에 체크된게 출력됨*/


            /*carSel = document.querySelector('.car option:checked');//select옵션이 선택되었을 경우

            mydiv.innerText=carSel.value;*/            

        }

    </script>

</head>

<body>

    <div id="mydiv"></div><br>


    <select class="car">

        <option value="i30">i30</option>

        <option value="아우디">아우디</option>

        <option value="BMW">BMW</option>

        <option value="벤츠">벤츠</option>

    </select>


    <fieldset>

        <legend>학년</legend>

        1학년 : <input type="radio" value="1학년" name="grade"><br>

        2학년 : <input type="radio" value="2학년" name="grade"><br>

        3학년 : <input type="radio" value="3학년" name="grade"><br>

    </fieldset>

    <br>

    <input type="checkbox">학생<br><br>


    <fieldset>

        <legend>취미</legend>

        <input type="checkbox" value="독서" name="hobby">독서<br>

        <input type="checkbox" value="영화감상" name="hobby">영화감상<br>

        <input type="checkbox" value="뜨게질" name="hobby">뜨게질<br>

    </fieldset><br>


    이름:<input type="text"><br><br>


    <textarea id="txtar" rows="10" cols="100"></textarea><br><br>


    <button onclick="fn()">확인</button>


</body>

</html>


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>


    <script>

    

        function fn() {

            //mydiv.innerHTML="<h1>korea</h1>";


            h1 = document.createElement('h1');

            h1.innerText="korea"

            mydiv.appendChild(h1);//div에 child로 h1태그가 적용된 korea가 나타난다. appendChild는 요소를 계속 추가한다.



            myli = document.createElement('li');

            //txt=document.querySelector('[type="text"]'); myli.innerText=txt.value;

            myli.innerText=myin.value;

            myul.appendChild(myli);//id가 myul인 곳에 child로 li태그가 적용된 input 값이 나타난다.



        }


    </script>


</head>

<body>

    <button onclick="fn()">확인</button>

    <input id="myin" type="text"><br>


    <ul id="myul">

        <li>test1</li>

        <li>test2</li>

        <li>test3</li>

    </ul>


    <div id="mydiv">확인</div>


</body>

</html> 



<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    

    <script>

        function fn() {


            /*xml parsing할 때 많이 쓰인다.*/

            //myul.firstElementChild.innerText="hello";//첫번재 요소를 바꾼다.

            //myul.firstElementChild.nextElementSibling.innerText="hello2";//첫번째 요소의 옆 형제 요소를 바꾼다.

            //myul.firstElementChild.nextElementSibling.nextElementSibling.innerText="hello3";//첫번째 요소의 옆, 옆 형제 요소를 바꾼다.

            //myul.nextElementSibling.innerText="hi"//ul 옆에 있는 div 텍스트를 바꾼다.


            //myul.children[0].innerText="hello";//ul에 대한 array를 가져온다.

            /*for(n=0; n<myul.children.length; n++){

                myul.children[n].innerText="hello";

            }*/


            //mydiv.firstElementChild.innerText="korea"

            //mydiv.nextElementSibling.innerText="korea2"

            //mydiv.firstChild.nodeValue="korea1";//자식이 아닌 div에 있는 요소 글자 바꿀 경우

            //mydiv.firstChild.nextSibling.firstChild.nodeValue="korea222"//div안에 있는 글자 옆의 div의 글자를 바꿀 경우


            //mydiv.childNodes[0].nodeValue="하이1...";//주어진 요소의 자식 노드 모음을 반환

            //mydiv.childNodes[1].firstChild.nodeValue="하이2...";//1번 div의 첫번째

            //mydiv.nextElementSibling.innerText="dd"




            /*elemnet 삭제*/

            /*tt=document.querySelector('#mydiv div');

            mydiv.removeChild();//mydiv.removeChile(mydiv.firstElementChild);*/


            mli=document.createElement('li');

            mli.innerText="korea";

            //myul.appendChild(mli);

            //myul.insertBefore(mli,myul.firstElementChild.nextElementSibling);//(a,b)이면 a를 b앞쪽에 추가해라

            myul.insertBefore(mli, app.nextElementSibling);



        }

    </script>


</head>

<body>


    <button onclick="fn()">확인</button>


    <div id="mydiv">헬로

        <div>하이</div>

    </div>


    <div>테스트</div>


    <ul id="myul">

        <li>사과1</li>

        <li>사과2</li>

        <li id="app">사과3</li>

        <li>사과4</li>

    </ul>


    <div>하이</div>



</body>

</html>



[BOM 다루기]


· BOM

- 브라우저 객체 모델(Browser Object Model)

- 웹 브라우저가 가지고 있는 모든 객체를 의미

- 최상위 객체 :  window -> 따라서 window 생략 가능함

- navigator, location, history, screen, document, frames 객체가 있다.


· window.open 속성

데이터 : 추가, 삭제, 검색, 정렬, 수정

array : push, splice...

json : 직접 객체 생성

- 객체명={속성:값, ....}

- function 클래스이름(인자..){

this.속성명=인자...

}

- obj = new 클래스이름(인자값)


[문자열 객체의 핵심 멤버함수]


   s="나는 자랑스런 태극기 앞에";//s=new String("나는 자랑스런 태극기 앞에")

s1="hello";
s2="hi";

console.log(s.charAt(3));//세번째 글자 출력
console.log(s.indexOf('스런'));//'스런'이 시작하는 index 출력
console.log(s.indexOf('헬로'));//문자열이 없을 때 -1 출력
console.log(s1.concat(s2));//s1 s2 두 문자열 연결해줌(=s1+s2)
console.log(s1.toUpperCase());//대문자로 변환 후, 출력
console.log(s.substring(3, 9));//3,4,5,6,7,8번째 글자 출력(9는 출력X)
console.log(s.split(' '));//''안의 문자로 문자열 잘려서 출력


    arr = [10, 20, 30, 40];

//arr.push(50);//맨 끝에 50추가
//arr.splice(1, 1, 100)//20삭제하고 100추가
n=arr.length;//배열의 개수(속성)
console.log(arr);

ar1=arr;//shallow copy
// ar1=arr.slice(0)//deep copy
ar1[0]=100;
console.log("slice", ar1);//100, 20, 30, 40으로 출력


ar1=arr.slice(2);//index:2인 속성부터 출력
console.log(ar1);


arr=[10,20,30,40,50];

arr.forEach(efn);//forEach는 매개변수로 함수 가짐
function efn(v, i) {//v:배열 값 i:index
console.log(v, i)
}//#1 함수 정의 후 호출

arr.forEach(function (v, i) {
console.log(v, i);
})//#2 바로 함수 호출

arr.forEach((v, i) =>{
console.log(v, i);})//#3 lambda 



arr=[10,20,30,40,50];

for(n=0; n<arr.length; n++){
console.log(arr[n])
}
for(n in arr){
console.log(arr[n])
}
for(n of arr){
console.log(n)
} 


jarr=[{'name':'홍길동', 'age':20},
{'name':'이순신', 'age':30},
{'name':'임꺽정', 'age':40},];

jarr.forEach(jfn);
function jfn(v, i) {//value, index
console.log(v, i);//값 출력하고 싶으면 (v.name, v.age)

} 



arr=[10,20,30,40,50,60,70];
farr=arr.filter(fFn);//filter함수 : 탐색, 검색
function fFn(v, i) {
console.log(v, i);
/*if(i%2==0) {//index 2로 나누고 나머지가 0일 경우
return true;
}*/

/*if(v>30){//value 30보다 큰 값일 경우
return true;
}*/

/*if(i>=2 && i<=4){//index 2이상 4이하일 경우
return true;
}*/
}

console.log('farr:', farr); 


jarr=[{'name':'홍길동', 'age':20},
{'name':'이순신', 'age':30},
{'name':'임꺽정', 'age':40},
{'name':'정난정', 'age':50},
{'name':'테스트', 'age':60}];

farr=jarr.filter(fFn);
function fFn(v, i) {
//console.log(v, i);//json index 출력
/*if(v.age>=40){//나이가 40 이상일 경우
return true;
}*/

/*if(v.name.indexOf('') != -1){//이름에 ''이 있는 경우
return true;
}*/

}

console.log('farr:', farr); 



[정렬]


<script>
//배열
arr=[100,20,30,400,50,60,70];
arr.sort(sfn);//callback함수 호출
function sfn(a, b) {
return a>b;//오름차순으로 정렬
return a<b;//내림차순으로 정렬
}
console.log(arr);

//json
jarr=[{'name':'홍길동', 'age':30},
{'name':'이순신', 'age':10},
{'name':'임꺽정', 'age':20},
{'name':'정난정', 'age':50},
{'name':'테스트', 'age':40}];

jarr.sort(jfn);
function jfn(a, b) {
//return a.age>b.age;//나이순 오름차순 정렬
return a.name>b.name;//이름순 가나다 정렬
}
console.log(jarr);

</script> 


Date 객체

날짜와 시간 작업을 하는데 사용되는 가장 기본적인 객체

new Date();  현재 날짜와 시간

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function init() {
dt = new Date();
console.log(dt);
y = dt.getFullYear();
m = dt.getMonth() + 1;//1월을 0으로 보기 때문에 getMonth()+1해줘야함
d = dt.getDate();

h = dt.getHours();
mi = dt.getMinutes();
sec = dt.getSeconds();

s = `${y}${m}${d}`;//formatString 쿼타
s1 = y + " " + m + " " + d + "";
s2 = `${h}${mi}${sec}`;

console.log(s);
console.log(s1);
console.log(s2);

//mydiv.innerText = s;//DOM 완성되기 전이기에 init함수 필수!
}
</script>
</head>
<body onload="init()"><!--DOM이 완성되면 onload 실행-->
<div id="mydiv">표시</div>
</body>

</html> 



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/*function fn() {
setTimeout(cfn, 3000);
//setInterval(cfn, 2000); //계속 호출
}
function cfn() {
mydiv.innerText="대한민국";
}//#1*/

/*function fn() {
setTimeout(function () {
mydiv.innerText="대한민국";
}, 3000);
}//#2*/

/*function fn() {
setTimeout(() => {
mydiv.innerText="대한민국";
}, 3000);
}//#3 lambda */

s="나는 자랑스런 태극기 앞에";
arr=s.split(' ');
n=0;

function fn() {
setTimeout(cfn, 3000);
myInt = setInterval(cfn, 2000); //계속 호출

}
function cfn() {
if(n==3){
n=0;
}
mydiv.innerText=arr[n];
n++
}
function fn1() {
clearInterval(myInt);
}
</script>
</head>
<body>
<div id="mydiv">표시</div>
<button onclick="fn()">확인</button>
<button onclick="fn1()">종료</button>
</body>

</html> 


[Number 객체]

a=10.341592;//a=new Number(10);
console.log(a.toFixed(2));//소수점 아래 2번째 자리까지 출력
console.log(a.toPrecision(4));//소수점 제외 숫자 4개 출력
s=a.toString();
console.log(s, typeof s);
b=parseFloat(s);
console.log(b, typeof b); 



        //s="i like phone like programing";

        //console.log(s.indexOf("javascript"));//앞에서부터 찾는다.

        //console.log(s.lastIndexOf("javascript"));//뒤에서부터 찾는다.


        //reg=new RegExp('[a-z]ike');//패턴에 해당하는 것들 중에서 첫번째 것만 찾아준다.

        //reg=new RegExp('[a-z]ike', 'g');//g옵션 주면 해당하는 것 다 찾아준다.

        //reg=new RegExp('p[a-z]+', 'g');

        //s1=s.match(reg);//s에서 reg 패턴에 해당하는 것을 찾아서 array로 return 해준다.

        //console.log(s1[0], s1[1]);



        /*a=10;//new Number(10)

        s2='abc';//new String('abc')

        arr=[];//new Array()

        j={};//new Object()

        reg=/p[a-z]+/g;//reg=new RegExp('p[a-z]+', 'g'))

        s1=s.match(reg);//s1=s.match(/p[a-z]+/g)*/



        /*s="i like phone like programing";

        s1=s.replace(/p[a-z]+/g, "love");//패턴에 해당하는 것을 찾아서 love로 바꿔준다.

        console.log(s1);//바뀐 문자열 return해준다.*/


        /*s2="hello-korea hi#like";

        ar=s2.split(/[- #]/g);

        console.log(ar);*/


        /*s="i like korea";

        console.log(s.substring(2,4));//substring과 slice 같다.

        console.log(s.slice(2,4));

        console.log(s.substr(2,3));//index:2부터 3개를 가져온다.*/ 


[Math 객체]

console.log(Math.PI);
console.log(Math.abs(-10));//절대값 출력
console.log(Math.pow(2,3));//2 3제곱=8
console.log(Math.ceil(33.76));//올림
console.log(Math.round(33.76));//반올림
console.log(Math.floor(33.76));//소수점 이하 버린다.
n=Math.random()*10;//0.xx~9.xx 사이 숫자 나온다.

console.log(Math.floor(n));//소수점 이하 버려서 0~9사이 숫자 나온다. 


[try catch]

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        /*function div(a,b) {

            if(b==0){

                throw "0으로 나누면 안됨"

        }

        return a/b;

        }


        try{

            rst=div(10,5);

            console.log(rst);

        }catch(err){

            console.log("에러:", err)

        }*/



        /*function isValid(v) {

            if(v==""){

                throw "값을 입력하세요.";

            }else if(isNaN(v)){//isNaN : 숫자가 아닐 때

                throw "숫자를 입력하세요.";

            }

            return v;

        }


        function fn() {

            try{

                my=isValid(myin.value);

                mydiv.innerText=my;

            }catch(err){

                console.log("에러:", err);

            }

        }*/


    </script>

</head>

<body>

    <div id="mydiv">결과</div>

    숫자 : <input id="myin" type="text"><br>

    <button onclick="fn()">확인</button>

</body>

</html> 


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        function fn() {

            aa=document.getElementById("mydiv");

            //aa.innerText="코리아";

            //mydiv.innerText='코리아';

            bb=document.getElementsByClassName("myc");//HTMLCollection

            bb=Array.from(bb);//HTMLCollection을 Array로 변경한다.


            /*bb.forEach(function (v, i) {

                console.log(v);

                v.innerText="대한민국";

            })//forEach문*/


            /*for(n in bb){ //for(n=0; n<bb.length; n++){

                console.log(n)

                //bb[n].innerText="대한민국";

            }//for in문*/


            //bb=Array.from(bb);

            //console.log(bb[0]);

            //bb[0].innerText="대한민국";

            //bb[1].innerText="대한민국1";

        }

    </script>

</head>

<body>

    <div id="mydiv">테스트</div>

    <div class="myc">테스트1</div>

    <div class="myc">테스트2</div>

    <button onclick="fn()">확인</button>

</body>

</html>


'SK고용디딤돌' 카테고리의 다른 글

직무교육 10일차(JavaScript)  (0) 2017.07.21
직무교육 9일차(JavaScript)  (0) 2017.07.20
직무교육 7일차(JavaScript)  (0) 2017.07.18
직무교육 6일차(JavaScript)  (0) 2017.07.17
직무교육 5일차(CSS)  (0) 2017.07.14

아이디 : <input type="text"><br>

패스워드 : <input type="password"><br>

정렬하기

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <style>

        .myaccount{

            display: table-row;

            height: 30px;

        }

        label, input{

            display: table-cell;

        }/*table로 정렬 맞춰주기*/

        [for="myid"]{

            letter-spacing: 5px;

        }/*아이디 글자 간격 조정해서 패스워드에 맞추기*/

    </style>

</head>

<body>


    <div class="myaccount">

        <label for="myid">아이디:</label><input id="myid" type="text">


    </div>


    <div class="myaccount">

        <label for="mypass">패스워드:</label><input id="mypass" type="password">

    </div>

</body>

</html> 


insert버튼으로 table에 데이터 추가하기

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>


    <script>

        function fn() {

            tr = mytable.insertRow();//row 객체 만든다.

            td1 = tr.insertCell();

            td2 = tr.insertCell();


            td1.innerText="Cell1";

            td2.innerText="Cell2";

        }


    </script>


</head>

<body>

    <button onclick="fn()">Insert</button>


    <table id="mytable" border="1">

        <tr>

            <th>Data1</th>

            <th>Data2</th>

        </tr>


    </table>


</body>

</html>


· json(자바스크립트 객체 타입)

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        myobj={aa:10, bb:3.14, cc:true, dd:"abc", fn:function () {

                alert("call");

            }//메소드 정의

        };//속성 정의

       myobj.aa=5;//속성 수정

       myobj.ee=100;//속성 추가

        console.log(myobj);

        console.log(myobj.aa, myobj.bb, myobj.cc, myobj.dd);

        console.log(myobj["aa"], myobj["bb"], myobj["cc"], myobj["dd"]);

        myobj.fn();//callable

    </script>

</head>

<body>

</body>

</html> 


· for in 문

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        myobj={aa:10, bb:20, cc:30};


        for(x in myobj){

            console.log(x);

        }


    </script>

</head>

<body>


</body>

</html> 



· 배열

arr = [10,20,30, 10.3, 'aaa', true];

 <!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        arr=[10, 20, 30, 40, 50];


        for(x in arr){

            console.log(x)

        }//index 출력


        for(x of arr){

            console.log(x);

        }//값 출력

    </script>

</head>

<body>


</body>

</html>


[예제]

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        /*function hap(a, b) {

            return a+b;

        }

        rst=hap(10, 20);

        console.log(rst);//두 수의 합 구하기*/


        /*function circle(r) {

            return r*r*3.14;

        }

        rst=circle(10);

        console.log(rst);//원의 넓이 구하기*/



        /*function big(a, b, c) {

            if(a<b && c<b){

                return b;

            }else if(a<c && b<c) {

                return c;

            }else{

                return a;

            }

        }

        rst=big(110,40,30);

        console.log(rst);//숫자 3개 중에서 최대값 구하기-논리연산자*/


        /*function max(a, b, c) {

            mymax = a>b ? a:b;

            mymax = mymax>c ? mymax:c;

            return mymax;

        }

        rst=max(110,40,30);

        console.log(rst);//숫자 3개 중에서 최대값 구하기-삼항연산자*/

        

    </script>

</head>

<body>


</body>

</html> 


· arguments 객체

- array로 넘겨준다.

- 가변인자이다.(매개변수 개수 불일치해도 실행된다.)

function testfn(a,b) {
console.log(arguments);
console.log(arguments[0], arguments[1]);
}

testfn(100,200) 


function mytest(a, ... v) {
console.log(a);
console.log(v);
}

mytest(10,20,30,40);//10 a에 들어가고 나머지는 v에 Array배열로 들어간다. 


· var a =10; 

- 지역변수->함수 안에서만 사용할 수 있다.


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Title</title>

    <script>

        a=100;

        function fn() {

            a=10;//전역변수

        }


        fn()

        console.log("a=", a)


    </script>

</head>

<body>


</body>

</html>


 for(n=1; n<=10; n++){//for(let n=1; n<=10; n++) let을 써주면 for문 안에서만 사용가능하다.

    console.log(n);
}
console.log("n=", n);//n=11로 출력된다.



· let

let 문을 사용하여 변수를 선언합니다. 범위는 변수가 선언되는 블록으로 제한됩니다.  변수를 선언할 때 또는 나중에 스크립트로 변수에 값을 할당할 수 있습니다.  

let을 사용하여 선언한 변수는 선언 전에 사용할 수 없으며, 그렇지 않으면 오류가 발생합니다.

let 문에서 변수를 초기화하지 않을 경우 JavaScript 값 undefined가 자동으로 할당됩니다.

함수 내부에서는 var 제어문 내부에서는 지역변수


· const

- 초기값을 변경할 수 없게 된다.

- 읽기전용


· splice 함수

/*index, 삭제할 개수, 추가할 값*/
arr.splice(1, 2);//index:1에서 2개를 삭제

  arr.splice(1,1,100);//index:1 1개를 삭제하고 그 위치에 100을 넣어라 

arr.splice(1, 0, 100)//추가


· 주소록 만들기

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

<title>Insert title here</title>

<style>

h1{

text-align: center;

}

div{

margin: auto;

}

input{

margin-bottom: 10px;

width: 150px;

}

#wrap{

text-align: center;

padding: 10px;

margin: auto;

border: 1px solid;

}

th{

border: solid;

}

table{

width: 300px;

margin: auto;

border-collapse: collapse;

}

</style>

<script>

myobj=new Array();

function insert() {

myobj.push({'myname':myname.value, 'myage':myage.value, 'mybirth':mybirth.value});

if(myname=="" || myage=="" || mybirth==""){

myobj.length=myobj.length-1;

}

myname.value="";

myage.value="";

mybirth.value="";

}

function fn() {

delRow();

for(n=0; n<myobj.length; n++){

tr=mytable.insertRow();

td1=tr.insertCell();

td2=tr.insertCell();

td3=tr.insertCell();

td1.innerText=myobj[n].myname;

td2.innerText=myobj[n].myage;

td3.innerText=myobj[n].mybirth;

}

function delRow() {

for(a=1; a<mytable.rows.length;){

mytable.deleteRow(a);

}

}

}

</script>

</head>

<body>

<h1>주소록</h1>

<div id="wrap">

이름:<input id="myname" type="text"><br>

나이:<input id="myage" type="number"><br>

생일:<input id="mybirth" type="date"><br><br>

<button onclick="insert()">입력</button> &nbsp;

<button onclick="fn()">보기</button><br><br>

<table id="mytable">

<tr>

<th>이름</th>

<th>나이</th>

<th>생일</th>

</tr>

</table>

</div>

</body>

</html> 


'SK고용디딤돌' 카테고리의 다른 글

직무교육 9일차(JavaScript)  (0) 2017.07.20
직무교육 8일차(JavaScript)  (0) 2017.07.19
직무교육 6일차(JavaScript)  (0) 2017.07.17
직무교육 5일차(CSS)  (0) 2017.07.14
직무교육 4일차(CSS)  (0) 2017.07.13

BOM.docx

자바스크립트


· 동적인 웹 페이지를 작성하기 위하여 사용되는 언어

· 객체 : 메모리가 할당된 Data Type

· 웹의 표준 프로그래밍 언어

· 모든 웹브라우저들은 자바스크립트를 지원

· 자바스크립트 특징

- 인터프리트 언어

- 동적 타이핑

- 구조적 프로그래밍 지원

- 객체 기반

- 함수형 프로그래밍 지원

- 프로토타입 기반


[컴퓨터 구조]

 · CPU

- 연산장치

- 제어장치

- 기억장치

· RAM

- 개발한 프로그램은 메모리 위에 올라감

- CPU와 RAM은 버스로 연결되어있음


[자바스크립트 학습순서]

데이터타입 → 연산자 → 제어문(if, switch, for, while) → 함수 → 클래스 → 라이브러리


[객체]

· DataType(정수, 실수, 문자열, 배열, json, 함수...)

- 10이라는 정수객체가 메모리 어딘가에 할당되있고 할당된 곳에대한 위치를 a라는 변수가 알고 있다.

10이라는 정수객체를 조작하는 방법은 속성과 메소드를 이용한다.

변수(객체).속성

변수(객체).메소드(..) 를 통해 조작한다.

· BOM : 미리 만들어져 있는 객체

· DOM : 메모리에 할당된 Tag 객체

- div, img, table ...

· HTML5 API

- 브라우저 자원(통신, 자료저장소, 쓰레드, 캐시, CANVAS, 위치정보)


· myDiv.innerText : 텍스트 내용 읽어오기


 <!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
function fn() {
n=parseInt(num.value)

if(90<=n && n<=100){
mydiv.innerText="A";
}else if(80<=n && n<=89) {
mydiv.innerText="B";
}else if(70<=n && n<=79){
mydiv.innerText="C";
}else if(60<=n && n<=69){
mydiv.innerText="D";
}else{
mydiv.innerText="F";
}
}
</script>
</head>
<body>
숫자:<input id="num" type="number"><br>
<div id="mydiv">결과</div>
<button onclick="fn()">확인</button>
</body>
</html>


'SK고용디딤돌' 카테고리의 다른 글

직무교육 8일차(JavaScript)  (0) 2017.07.19
직무교육 7일차(JavaScript)  (0) 2017.07.18
직무교육 5일차(CSS)  (0) 2017.07.14
직무교육 4일차(CSS)  (0) 2017.07.13
직무교육 3일차(CSS)  (0) 2017.07.12

모바일 화면 볼 수 있는 사이트

http://troy.labs.daum.net/


애니메이션


 · transition : width 5s;


- 5초동안 width 바뀜


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style type="text/css">

div{

width: 100px;

height: 100px;

background-color: yellow;

transition: width 4s, height 4s, color 4s;

transition-delay:1s;

}

div:hover{

width:200px;

height: 200px;

color: red;

text-align: center;

}

img{

width:200px;

height: 150px;

opacity: 0.1;

/* transition: opacity 1s; */

transition-property: opacity;

transition-duration: 2s;

transition: width 4s, height 4s;

}

img:hover{

opacity: 1;

width: 300px;

height: 300px;

}

</style>

</head>

<body>

<img src="image/bbb.jpg"><br>

<div>transition예제</div>

</body>

</html> 


'SK고용디딤돌' 카테고리의 다른 글

직무교육 7일차(JavaScript)  (0) 2017.07.18
직무교육 6일차(JavaScript)  (0) 2017.07.17
직무교육 4일차(CSS)  (0) 2017.07.13
직무교육 3일차(CSS)  (0) 2017.07.12
직무교육 2일차(HTML)  (1) 2017.07.11

· iframe 높이 자동 계산


 <script type="text/javascript">

  function resizeIframe(obj)

  {

     obj.style.height = 0;

     obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';

  }

</script>


<iframe onload="resizeIframe(this)" name="my" frameborder="0" width="100%"></iframe>


· table 경계선 없애기

- border-collapse: collapse;


· table 화면에 꽉차게 넣기

- width: 100%;


· 둥근 테두리

- border-radius: 10px;(px값 높아질수록 둥그러진다 -> 원형태로 됨)


· 경계선 그림자

- box-shadow: 5px 5px 5px red;


· 마진과 패팅

- auto : 브라우저가 마진을 계산한다.

- length : 마진을 px, pt, cm단위로 지정할 수 있다.

- % :마진을 요소 폭의 퍼센트로 지정한다.

- ingerit : 마진이 부모 요소로부터 상속된다.


margin : 10px 20px 30px 40px

top   right  botttom  left


· 웹 페이지를 만들 때 wrap 설정해주기

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

#wrap{

width: 1000px;

height: 650px;

/* margin: 50px auto; */

text-align: center;

background-color: green;

}

#mydiv{

/* margin: auto; */

width: 50%;

background-color: yellow;

}

</style>

</head>

<body>

<div id="wrap">

<div id="mydiv">test</div>

<img src="image/b.jpg">

</div>

</body>

</html>


- <div id="wrap"> 설정을 안해주면 글자 흘러내린다


· 배경 설정하기

body{

background-image: url("image/a.jpg");

background-repeat: repeat; 

background-attachment: fixed;

- 배경이미지 고정해놓기


· 리스트 스타일

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

ul{

list-style-type: square;

list-style-image: url("image/icon.png");

list-style-position: inside;

}

</style>

</head>

<body>

<ul>

<li>사과</li>

<li>포도</li>

<li>딸기</li>

</ul>

</body>

</html> 


· 블록요소를 인라인요소로 바꾸기

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

div{

display: inline;

}/*블록요소를 인라인요소로 바꾸기*/

        span{

display: block;

}/*인라인요소를 블록요소로 바꾸기*/

</style>

</head>

<body>

<div>테스트1</div>

<div>테스트2</div>

<div>테스트3</div>

</body>

</html> 



· 글자간 간격 주기

- letter-spacing: 10px;


· <a href>에 밑줄 없애기

- text-decoration: none;


· table에서 텍스트 수평 정렬 ->text-align: center;


· table에서 텍스트 수직 정렬 -> vertical-align: top;


· 레이아웃


· visibility: hidden;

- 숨겨지지만 자리는 차지함


· display: none;

- 숨겨지고 자리 차지도 하지않음


· z-index

- 숫자가 높을수록 앞에 나옴


· width와 max-width 차이

- 인터넷 창 크기가 작아져도 max-width(동적)는 같이 작아지지만, width(정적)는 가려짐

- min-width: 500px; : 100%유지하다가 인터넷 창 크기 자아지면 50%로 유지


· opacity

- 투명도 설정

'SK고용디딤돌' 카테고리의 다른 글

직무교육 6일차(JavaScript)  (0) 2017.07.17
직무교육 5일차(CSS)  (0) 2017.07.14
직무교육 3일차(CSS)  (0) 2017.07.12
직무교육 2일차(HTML)  (1) 2017.07.11
직무교육 1일차(HTML)  (0) 2017.07.10

wsu-css-cheat-sheet.pdf


문서의 구조 : HTML

문서의 스타일 : CSS(Cascading Style Sheets)


거대하고 복잡한 사이트를 관리할 때 필요

모든 페이지들이 동일한 CSS 공유


· CSS의 구성

- 선택자(selectors)

- 박스 모델

- 배경 및 경계선

- 텍스트 효과

- 2차원 및 3차원 변환

- 애니메이션

- 다중 컬럼 레이아웃

- 사용자 인터페이스


· CSS3의 문법

- 선택자(selector) { 속성 : 값 ; }

ex) p{background-color : yellow;}

- 주석 : /* ... */


<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

div{

속성:값;

속성:값;

...

}

</style>

</head>

<body>

<div>css3 test</div>

</body>

</html>



· 적용 순서 : 임베디드 방식 -> 인라인 방식 -> css파일


· <link rel="stylesheet" href="css/a.css">

- html <head>안에 추가해주기


· 선택자 : HTML 요소를 선택하는 부분(선택자는 jQuery에서도 사용)


· 선택자 종류

- 타입 선택자

=HTML 요소 이름 선택

<style>

h1{

color:blue;

}

div{

color: green;

}

</style> 


- 전체 선택자 

= 페이지 안에 있는 모든 요소 선택

*{

background-color: yellow;


- 클래스 선택자 : .

= 클래스가 부여된 요소를 선택

= 클래스 이름 중복 선언 O

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

.my1{

color: yellow;

}

</style>

</head>

<body>

<div class="my1">test</div>

<p class="my1">테스트1</p>

<p>테스트2</p>

</body>

</html> 

= p.my1{

color:red;

}

-> p 태그 중에서 클래스 이름이 my1인 것만 적용됨


- 아이디 선택자 : #

= 특정한 요소를 선택

= id 중복 선언 X -> 처음 등장하는 것 하나만 적용됨

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<style>

#test1{

color: red;

text-align: center;

}

</style>

</head>

<body>

<p id="test1">테스트1</p>

</body>

</html> 


- 속성 선택자

= 특정한 속성을 가지는 요소를 선택

<style>

[src]{

border: 3px solid red;

}

        [class]{

color: red;

}

</style>

= p[class]{ } ->p태그 안에 있는 class 속성에만 적용


       [src="image/b.jpg"]{

border: 3px solid red;

}src가 일치하는 거

[src^="image"]{

border: 3px solid red;

}image로 시작하는 거

[src$="jpg"]{

border: 3px solid red;

} jpg로 끝나는 거 

[src*="c"]{

border: 3px solid red;

} src에 c가 들어있는 거 

       [name~="abc"]{

color: green;

} abc 있는거(공백포함)

[name|="abc"]{

color: green;

} abc- 있는거


<style>

[src="image/b.jpg"]{

border: 3px solid red;

}src가 일치하는 거

[src^="image"]{

border: 3px solid red;

}image로 시작하는 거

[src$="jpg"]{

border: 3px solid red;

} jpg로 끝나는 거

[src*="c"]{

border: 3px solid red;

} src에 c가 들어있는 거

p[class]{

color: red;

}

[name~="abc"]{

color: green;

}

[name|="abc"]{

color: green;

}

</style> 



- 의사 선택자(pseudo-selector)

<!-- 반응형 선택자 -->

<style>

div:hover{

color: red;

}/* hover : div 태그에 마우스 올라갔을 때 */

p:active {

background-color: yellow;

}/* active : p 태그 마우스로 클릭했을 때 */

[type="text"]:focus {

background-color: skyblue;

border: 2px solid white;

}/* focus : 마우스 커서가 위치했을 때 */ 

a:link{

color: blue;

}/*  */

a:visited{

color: green;

}/* a태그 클릭해서 방문했을 때 */

a:hover {

color: yellow;


li:last-child {

color: red;

}마지막 요소만 적용됨

li:first-child {

color: red;

}

li:nth-child(3n) {

color: red;


p:first-line {

background-color: yellow;

}

p:first-letter {

font-size: 50pt;

color: red;

}

p:before {

content: "CSS3";

color: green;

}

p:after {

content: "배우기";

color: green;


<style>

[name="color"]:checked{

width: 20px;

height: 20px;

}

div{

width: 100px;

height: 50px;

background-color: yellow;

}

[type="checkbox"]:checked{

width: 20px;

height: 20px;

}

#test1:enabled{

background-color: skyblue;

}

#test2:disabled{

background-color: blue;

}

input:required{

background-color: green;

}

input:read-only{

background-color: lightgray;

}

</style> 


nth-of-type : 


nth-child


· 자손, 자식 형제 결합자

- s1 s2 : 자식+후손

- s1>s2 : 자식만

- s1 +(오른쪽에 있는 형제만)/~(동급 레벨 모든 형제) s2: 형제

<style>

.test1 ~ div{

color: red;

}

.fruit ~ ul>li{

color: yellow;

}

</style> 


· font - 웹폰트

- 모든 유저가 동일한 폰트를 볼 수 있고 라이센스 문제 해결

<style>

@font-face{

font-family: "나의글꼴";

src:url("font/NANUMGOTHIC.TTF");

}

*{

font-family : "나의글꼴";

}

</style> 


'SK고용디딤돌' 카테고리의 다른 글

직무교육 5일차(CSS)  (0) 2017.07.14
직무교육 4일차(CSS)  (0) 2017.07.13
직무교육 2일차(HTML)  (1) 2017.07.11
직무교육 1일차(HTML)  (0) 2017.07.10
SK고용디딤돌 1, 2주차 후기  (0) 2017.07.08

+ Recent posts