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

+ Recent posts