독학/JavaScript

JavaScript 독학1

나아눙 2022. 8. 27. 16:33

출력문

출력명령문

document.write("내용")

 

따옴표 표현하기

  1. document.write("\"");

문자열 연결 +

  1. <script>
  2. document.write("Mickey"+"Mouse");
  3. </script>

숫자를 문자화

<script>

document.write("6+6은 ? " + (6+6));

12

 

document.write("6+6은 ? " + ('6'+'6'));

66

</script>

 

alert

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
    alert('5*6='+5*6);
</script>
</head>
<body>
</body>
</html>

변수

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
    num = 30;
    str = "hi.";
    document.write(num);
    document.write("<br />");
    document.write(str);
</script>
</head>
<body>
</body>
</html>

 

변수 선언 법칙

변수명에는 영문 숫자 _

                   대문자,소문자 구별

                   첫 문자는 숫자가 올수 X

                   예약어 사용X

예약어의 종류

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

상수

const 상수명 = 값;

한번 값을 대입하면 다른 값 대입 X

 

데이터 형

 

따옴표

  1. '\''
  2. "\""
  3. "'"
  4. '"'

배열

  1. 변수명 = new Array();
  2. 변수명 = [값,값,값,값];
  3. document.write(변수명[0]);

boolean

  1. var bool = true;
  2. document.write(bool);
  3. document.write('<br>');
  4. bool = false;
  5. document.write(bool);

배열 값 추가하기

배열의 가장 뒤에 값 추가

배열변수명.push(추가할 값);

 

배열 앞에 값 추가

배열변수명.unshift(추가할 값);

 

배열의 수(길이) 알아보기

배열변수.length

 

데이터형 확인하기 typeof

typeof(변수 또는 상수)

 

형변환 - 데이터를 숫자로 변환하기 parseInt

parseInt(변수)

 

var str ="String"

str = parseInt(str)

=> NaN(Not a Number)

 

var str ="55"

str = parseInt(str)

=> 55 (문자열 -> 숫자)

 

var str ="숫자55"

str = parseInt(str)

=> NaN (숫자로 변환X)

 

var str ="55숫자"

str = parseInt(str)

=> 55(문자열 -> 숫자)

 

형변환 - 데이터를 숫자로 변환하기 Number

 

  1. Number(변수)

숫자로 시작하더라도 문자열이 들어가있다면 NaN로 값 변경

 

형변환 - 데이터를 숫자로 변환하기 String

  1. String(변수)

숫자 -> 문자열

 

형변환 - 데이터를 논리형으로 변환하기 Boolean

var num = 55

Boolean(str) = true

 

var str = "55"

Boolean(str) = true

 

var num = 0 

Boolean(str) = false

 

var str = "false"

Boolean(str) = true

 

날짜값 가져오기 date

현재의 날짜 데이터를 가져오는 방법

new Date()

 

const NOW_DATE = new Date();

 

년도값 가져오기 

const NOW_DATE = new Date();

document.write(NOW_DATE.getFullYear());

 

현재 월 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getMonth());

월은 0부터 반환하므로 +1를 해준다.

  1. const NOW_DATE = new Date();
  2. const NOW_MONTH = NOW_DATE.getMonth() + 1;
  3. document.write(NOW_MONTH);

현재 일 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getDate());

현재 요일 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getDay());

일요일 0 월요일 1 화요일 2 수요일 3 목요일 4 금요일 5 토요일 6

  1. <script>
  2. const NOW_DATE = new Date();
  3. var nowDay = "";
  4. switch(NOW_DATE.getDay()){
  5. case 0:
  6. nowDay = "일요일";
  7. break;
  8. case 1:
  9. nowDay = "월요일";
  10. break;
  11. case 2:
  12. nowDay = "화요일";
  13. break;
  14. case 3:
  15. nowDay = "수요일";
  16. break;
  17. case 4:
  18. nowDay = "목요일";
  19. break;
  20. case 5:
  21. nowDay = "금요일";
  22. break;
  23. case 6:
  24. nowDay = "토요일";
  25. break;
  26. default :
  27. nowDay = "알수없는요일";
  28. break;
  29. }
  30. document.write("오늘은 " + nowDay);
  31. </script>

현재 시 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getHours());

현재 분 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getMinutes());

현재 초 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getSeconds());

현재 밀리초 값 가져오기

  1. const NOW_DATE = new Date();
  2. document.write(NOW_DATE.getMilliseconds());

글로벌 변수와 로컬 변수

글로벌 변수 : 전역 변수 

로컬 변수 : 지역 변수 

  1. <script>
  2. function hello(){
  3. document.write("Hello world");
  4. }
  5. hello();
  6. </script>
  1. <script type="text/javascript">
  2.  
  3. glo_var = 10;
  4. function hello(){
  5. local_var = 20;
  6. }
  7.  
  8. document.write(glo_var);
  9. //document.write(loaca_var); 출력 안됨
  10. </script>

로컬 변수 앞에 var가 있으면 함수 안에서만 작동

로컬 변수 앞에 var가 없으면 해당 함수가 한번 호출하고 글로벌 변수가 된다.

  1. <script type="text/javascript">
  2.  
  3. glo_var = 10;
  4. function hello(){
  5. var local_var = 20;
  6. local_var2 = 30;
  7. }
  8. hello(); //해당 함수 호출
  9. document.write(local_var2); //전역 변수가 된다.
  10.  
  11. </script>

연산자

== 은 값이 같다면 참이지만 ===은 값과 타입까지 같아야 참

!= 은 값이 다르면 참이지만 !==은 타입도 다르고 값도 달라야 참

 

if문 

if else if else

 

삼항연산자

  1. <script>
  2. document.write(( 1 == 1) ? "true" : "false");
  3. </script>

switch

  1. switch (변수명){
  2. case A :
  3. 값이 A 실행할 명령문;
  4. break;
  5. case B :
  6. 값이 B 실행할 명령문;
  7. break;
  8. case C :
  9. 값이 C 실행할 명령문;
  10. break;
  11. case D :
  12. 값이 D 실행할 명령문;
  13. break;
  14. case E :
  15. 값이 E 실행할 명령문;
  16. break;
  17. default :
  18. 위의 A ~ E 모두 아닐때 실행할 명령문;
  19. }

while

 

  1. while(조건){
  2. 조건에 만족할 동안 실행할 명령문
  3. }

do{
조건식이 참이면 실행할 명령은 여기에 적습니다.
}
while(여기에는 조건식을 적습니다.)

일단 한번 실행을 한후 조건문 검사후 참이면 실행 아니면 빠져나옴

 

for

  1. for(변수 선언 초기값 설정;조건식;증감식){
  2. 조건이 참인 동안 실행할 명령문;
  3. }

이중for문

  1. for(변수 선언 초기값 설정; 조건식; 증감식){
  2. for(변수 선언 초기값 설정; 조건식; 증감식){
  3. }
  4. }

continue문과 break문

continue문 만나면 해야할 명령문 실행하지 않고 그다음 명령문을 실행

 

break문 만나면 바로 빠져나가는 명령문 

 

confirm창

 

확인 누르면 true , 취소 누르면 false

return

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>자바스크립트</title>
  6. <script>
  7. function hey(a,b){
  8. add = a+b;
  9. return 20;
  10. }
  11. document.write(hey(1,2));
  12. </script>
  13. </head>
  14. <body>
  15. </body>
  16. </html>

3을 반환하지 않고 20 을 반환 

 

함수 참조

함수명(); -> 함수 호출

함수명; -> 함수 참조

함수 참조는 함수를 다른 변수에 대입 할수 있다.

  1. <script>
  2. function funcRef(){
  3. return "ref";
  4. }
  5.  
  6. var hello = funcRef;
  7. document.write(hello());
  8. </script>

함수 표현식

 

함수 선언식

  1. function 함수명(){
  2. }

함수 표현식

  1. var sum = function(){
  2.  
  3. };
  4. sum();
  1. <script>
  2. var sum = function(param1, param2 = 3, param3 = 10){
  3. document.write(param1 + param2 + param3 + '<br>');
  4. }
  5.  
  6. sum(1);
  7. sum(1,2);
  8. sum(1,2,3);
  9. </script>
  10. </head>

함수 선언식은 함수를 먼저 호출하는 코드를 넣은후 함수 선언해도 상관없지만

함수 표현식은 함수가 먼저 선언한 후에 함수를 호출해야한다.

 

 

함수 화살표 표기법

 

  1. 변수(함수명) = () => 리턴할 값;
  1. <script>
  2. const arrowFunc = () => 'in arrow function';
  3.  
  4. document.write(arrowFunc());
  5. </script>

() -> 파라미터 명

' ' -> '$(파라미터명)

  1. <script>
  2. const arrowFunc = year => `I was born ${year}`;
  3.  
  4. document.write(arrowFunc(2005));
  5. </script>
  1. 변수(함수명) = 파라미터명 => { 명령문 };
  1. <script>
  2. const arrowFunc = sum => {
  3. const sumValue = sum + 10;
  4. return sumValue;
  5. };
  6.  
  7. document.write(arrowFunc(2005));
  8. </script>
  9. </head>
  1. 변수(함수명) = (파라미터명,파라미터명) => 리턴할 값;
  1. <script>
  2. const arrowFunc = (num, num2) => num + num2;
  3.  
  4. document.write(arrowFunc(1999,2020));
  5. </script>

hoisting(호이스팅)

 

함수선언식 호이스팅

  1. <script>
  2. hoisting();
  3.  
  4. function hoisting(){
  5. document.write('I am here');
  6. }
  7. </script>

함수 선언전에 함수를 호출해도 결과가 잘 나타남

 

함수표현식 호이스팅

  1. <script>
  2. hoisting();
  3.  
  4. const hoisting = function(){
  5. document.write('I am here');
  6. }
  7. </script>

함수 선언하고 호출

 

화살표표기법 호이스팅

  1. <script>
  2. document.write(hoisting());
  3.  
  4. const hoisting = () => 'I am here';
  5. </script>

함수 선언하고 호출 

 

변수선언 let 

let 변수명 = 값;범위 : 블록 단위

  1. <script>
  2. let num = 11;
  3.  
  4. if(true){
  5. let num = 20;
  6. document.write('num of inside is ' + num);
  7. }
  8.  
  9. document.write('<br>num of outside is ' + num);
  10. </script>
  11. </head>

안이랑 밖 변수 num이 다르다.

 

범위 - 스코프(scope)

let 또는 const 사용하여 변수 또는 상수를 선언하면

해당 블록안에서만 작동한다.

 

전역변수

  1. <script>
  2. let score = 100;
  3. {
  4. score = 55;
  5. document.write('in block = ' + score);
  6. }
  7. document.write('<br>out block = ' + score);
  8. </script>

in block = 55

out block = 55

 

  1. <script>
  2. {
  3. const score = 100;
  4. document.write('first block ' + score);
  5. }
  6.  
  7. {
  8. const score = 200;
  9. document.write('<br>second block = ' + score);
  10. }
  11.  
  12. {
  13. const score = 300;
  14. document.write('<br>third block = ' + score);
  15. }
  16. </script>

블록 내의 서로 다른 상수

 

객체 생성

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>자바스크립트</title>
<script>
    function make(){
        this.name;
        this.company;
        this.color;
        this.numPeople;
        this.meth = show;
    }
    function show(){
        document.write("이름 : "+this.name+"<br />");
        document.write("회사 : "+this.company+"<br />");
        document.write("인원 : "+this.numPeople +"<br />");
        document.write("색상 : "+ this.color +"<br />");
    }
    r = new make();
    r .name="sy";
    r.company = "sk";
    r.color = "pink";
    r.numPeople = 2;
    r.meth();
</script>
</head>
<body>
</body>
</html>

 

함수 파라미터 해제

 

연산자를 사용해 객체의 값에 접근

  1. <script>
  2. const myDeviceData = { name : 'sy', cpu : 'B', display : 9 };
  3.  
  4. function myDevice(data){
  5. document.write(data.name + '<br>');
  6. document.write(data.cpu + '<br>');
  7. document.write(data.display);
  8. }
  9.  
  10. myDevice(myDeviceData);
  11. </script>

객체의 키값으로 값에 접근

  1. <script>
  2. const myDeviceData = { name : 'sy', cpu : 'B', display : 9 };
  3.  
  4. function myDevice({name, cpu, display}){
  5. document.write(`${name}` + '<br>');
  6. document.write(`${cpu}` + '<br>');
  7. document.write(`${display}`);
  8. }
  9.  
  10. myDevice(myDeviceData);
  11. </script>

화면(모니터) 크기 알아내기

 

console에 screen치면 나옴

availHeight 는 상단 메뉴바와 하단 Dock Bar를 제외한 화면 세로길이

 

웹브라우저 창 크기 알아내기

자바스크립트에는 기본적으로 갖춘 객체 중 window객체가 있다.

window객체에는 웹브라우저에 대한 정보를 담고있다.

 

console에 window를 침

 

웹브라우저 가로 길이 = window.outerWidth
웹브라우저 세로 길이 = window.outerHeight
실제 웹페이지가 보이는 화면 가로 길이 = window.innerWidth
실제 웹페이지가 보이는 화면 세로 길이 = window.innerHeight

 

설렉터(선택자)

 

1.class selector

document.getElementsByClassName(클래스명)[순서];

 

script는 태그와 관련된 작업을 시작할때 HTML태그가 모두 로딩 된후 시작

 

window.onload = function(){ 코드 };

 

  1. <script>
  2. window.onload = function(){
  3. document.getElementsByClassName('hello')[2].style.color = "red";
  4. };
  5. </script>

 

  1. <body>
  2. <p class="hello">Hello World</p>
  3. <p class="hello">Hello World</p>
  4. <p class="hello">Hello World</p>
  5. <p class="hello">Hello World</p>
  6. <p class="hello">Hello World</p>
  7. <p class="hello">Hello World</p>
  8. <p class="hello">Hello World</p>
  9. </body>

p태그가 인지가 되고 3번째 hello world가 빨간색으로 변한다.

 

Tag Selector

document.getElementsByTagName(태그명)[순서];

  1. <script>
  2. window.onload = function(){
  3. document.getElementsByTagName('p')[5].style.color = "red";
  4. };
  5. </script>

document.getElementById(ID명);

  1. <script>
  2. window.onload = function(){
  3. document.getElementById('hello').style.color = "red"; //getElements -> getElement
  4. };
  5. </script>
  1. <body>
  2. <p>Hello World</p>
  3. <p>Hello World</p>
  4. <p>Hello World</p>
  5. <p id="hello">Hello World</p>
  6. <p>Hello World</p>
  7. <p>Hello World</p>
  8. <p>Hello World</p>
  9. <p>Hello World</p>
  10. </body>

querySelector 사용하기

  1. <script>
  2. window.onload = function(){
  3. document.querySelector('.hello').style.color = "blue";
  4. document.querySelector('p').style.color = "red";
  5. document.querySelector('#hello').style.color = "yellow";
  6. };
  7. </script>
  1. <body>
  2. <p>Hello World</p>
  3. <p class="hello">Hello World</p>
  4. <p class="hello">Hello World</p>
  5. <p id="hello">Hello World</p>
  6. <p>Hello World</p>
  7. <p>Hello World</p>
  8. <p>Hello World</p>
  9. <p>Hello World</p>
  10. </body>

순서 지정 X ->querySelectorAll (순서지정)

 

querySelectorAll 사용하기

  1. <script>
  2. window.onload = function(){
  3. document.querySelectorAll('.hello')[0].style.color = "blue";
  4. document.querySelectorAll('.hello')[1].style.color = "blue";
  5. document.querySelector('#hello').style.color = "yellow";
  6. document.querySelectorAll('p')[4].style.color = "red";
  7. document.querySelectorAll('p')[5].style.color = "red";
  8. };
  9. </script>

설렉터(선택자)의 텍스트 값 얻기(추출)와 변경하기

innerText를 사용하여 텍스트 얻는 방법

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
    window.onload = function(){
        document.write('내가 좋아하는 강아지는 ' + document.getElementsByClassName('dog')[1].innerText);
    }
</script>
</head>
<body>
    <p class="dog">말티즈</p>
    <p class="dog">리트리버</p>
    <p class="dog">푸들</p>
</body>
</html>

 

innerText 사용하여 텍스트를 변경하는 방법

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript</title>
<script>
    window.onload = function(){
        document.getElementsByClassName('dog')[1].innerText = "웰시코기"
    }
</script>
</head>
<body>
    <p class="dog">말티즈</p>
    <p class="dog">리트리버</p>
    <p class="dog">푸들</p>
</body>
</html>

설렉터(선택자)의 HTML 태그값 얻기(추출)와 변경하기

innerHTML 사용하여 HTML 태그를 얻는(추출) 방법

선택자.innerHTML

document.getElementById('dog').innerHTML

  1. <script>
  2. window.onload = function(){
  3. console.log(document.getElementsByClassName('dog')[1].innerHTML);
  4. }
  5. </script>
  1. <body>
  2. <p class="dog">
  3. <b>말티즈</b>
  4. </p>
  5. <p class="dog">
  6. <b>리트리버</b>
  7. </p>
  8. <p class="dog">
  9. <b>푸들</b>
  10. </p>
  11. </body>

innerHTML 사용하여 HTML 태그를 변경하는 방법

선택자.innerHTML = 변경할HTML태그

document.getElementById('os').innerHTML = "변경할 HTML 태그"

  1. <script>
  2. window.onload = function(){
  3. txt = document.getElementsByClassName('dog')[1].innerHTML;
  4. txt = '<i>' + txt + '</i>'
  5. document.getElementsByClassName('dog')[1].innerHTML = txt;
  6. }
  7. </script>
  1. <body>
  2. <p class="dog">말티즈</p>
  3. <p class="dog">리트리버</p>
  4. <p class="dog">푸들</p>
  5. </body>

태그의 개수(길이) 알아보기

선택자.length

1.document.getElementsByTagName('p').length;

 

클릭 이벤트 생성

1.inline방식

<p onClick="명령문">click here</p>

  1. <body>
  2. <p onClick="alert('Hi');">click here</p>
  3. </body>

2.script태그에서 클릭이벤트 발생시키기

선택자.addEventListener('이벤트 유형', function(){ 명령문; });

  1. <script>
  2. window.onload = function(){
  3. var target = document.getElementsByTagName('p')[0];
  4. target.addEventListener('click', function(){
  5. alert('Hi');
  6. });
  7. };
  8. </script>

마우스 이벤트 생성

<!--마우스 포인터를 올렸을때 mouseover
    마우스 포인터를 뗐을때 mouseout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouseover event</title>
<script>
    window.onload = function(){
        var target = document.getElementsByTagName('p')[0];
        target.addEventListener('mouseover', function(){
            target.style.color = "pink";
        });

        target.addEventListener('mouseout', function(){
            target.style.color = "black";
        });
    };
</script>
</head>
<body>
    <p>here</p>
</body>
</html>-->

<!--마우스 버튼을 누른상태에서 mousedown
    마우스 버튼을 떼면 mouseup
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouseover event</title>
<script>
    window.onload = function(){
        var target = document.getElementsByTagName('p')[0];
        target.addEventListener('mousedown', function(){
            target.style.color = "pink";
        });

        target.addEventListener('mouseup', function(){
            target.style.color = "black";
        });
    };
</script>
</head>
<body>
    <p>here</p>
</body>
</html>-->

 

<!--inline 방식-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>onmouse event</title>
</head>
<body>
    <p
    onMouseover="this.style.color='red';"
    onMouseout="this.style.color='black';"
    onMousedown="this.style.color='yellow';"
    onMouseup="this.style.color='pink';" >
        here
    </p>
</body>
</html>

 

스크롤 이벤트 생성

scroll 이벤트 사용방법

  1. document.addEventListener('scroll', function() {
  2.  
  3. });

현재의 스크롤 값 확인

document.documentElement.scrollTop;

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>pinkcoding - JavaScript - onmouseover event</title>
  6. <script>
  7. document.addEventListener('scroll', function() {
  8. var Value = document.documentElement.scrollTop;
  9. console.log('Value is ' + currentScrollValue);
  10. });
  11. </script>
  12. <style>
  13. div{height:3000px}
  14. </style>
  15. </head>
  16. <body>
  17. <div></div>
  18. </body>
  19. </html>
  20.  

console에서 스크롤 내리자 결과값이 나옴

체인지(변경) 이벤트 생성

1.inline 방식

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>change event</title>
</head>
<body>
    <select onChange="alert(this.value)">
        <option value="value">value</option>
        <option value="value2">value2</option>
        <option value="value3">value3</option>
    </select>
</body>
</body>
</html>

2.script태그에서 체인지 이벤트 실행하기

선택자.addEventLister('이벤트 유형', function(){ 명령문; });

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>change event</title>
<script>
    window.onload = function(){
        var target = document.getElementsByTagName('select')[0];
        target.addEventListener('change', function(){
            alert(this.value);
        });
    };
</script>
</head>
<body>
    <select>
        <option value="말티즈">말티즈</option>
        <option value="리트리버">리트리버</option>
        <option value="푸들">푸들</option>
    </select>
</body>
</html>

스타일 조정하기

선택자.style.background = "pink";

선택자.style.fontSize = "30px";

 

선택자{box-shadow:가로길이값 세로길이값 번짐 효과 그림자 색}

-> 선택자.style.boxShadow = "10px 10px 10px lightblue";

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
    var target = document.getElementsByTagName('div')[0];
    target.style.width = "500px";
    target.style.height = "20px";
    target.style.background = "pink";
    target.style.boxShadow = "10px 10px 10px lightpink";
};
</script>
</head>
<body>
    <div></div>
</body>
</html>

 

태그 속성 조정하기 

 

태그에 속성을 추가하는 방법

선택자.setAttribute(속성명, 속성값)

<!--<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>attribute</title>
<script>
window.onload = function(){
    var target = document.getElementsByTagName('p')[0];
    target.setAttribute('class','hi');
};
</script>
</head>
<body>
    <p>here</p>
</body>
</html>-->

 

속성의 값을 가져오는 방법

선택자.getAttribute(속성명)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
    var target = document.getElementsByTagName('input')[0];
    var attrValue = target.getAttribute('type');
    console.log('attrValue is ' + attrValue);
};
</script>
</head>
<body>
    <input type="button" />
</body>
</html>
-->

속성을 제거하는 방법

선택자.removeAttribute(속성명)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
    var target = document.getElementsByTagName('input')[0];
    var attrValue = target.getAttribute('type');

    if(attrValue == "button"){
        target.removeAttribute('type');
    }
};
</script>
</head>
<body>
    <input type="button" />


</body>
</html>-->

 

속성 유무 파악하기

선택자.hasAttribute(속성명);

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>style</title>
<script>
window.onload = function(){
    var target = document.getElementsByTagName('input')[0];
    var attr = target.hasAttribute('type');

    if(attr === false){
        target.setAttribute('type','button');
        target.setAttribute('value',"Button");
    }
};
</script>
</head>
<body>
    <input />
</body>
</html>

 

체크박스 체크하기

체크박스가 체크된 상태인지 아닌지 알아보는 방법

선택자.checked

 

체크박스를 체크상태로 만드는 방법

선택자.checked = true;

 

반대로 체크된 박스를 체크 안된 상태로 만드는 방법

선택자.checked = false;

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>checkbox</title>
<script>
window.onload = function(){
    document.getElementById('checked').checked = false;
    document.getElementById('unchecked').checked = true;
};
</script>
</head>
<body>
    <label for="checked">checked</label>
    <input type="checkbox" id="checked" checked/>
    <label for="unchecked">unchecked</label>
    <input type="checkbox" id="unchecked" />
</body>
</html>

 

여러개의 체크박스 체크하기

name 속성만으로 선택자를 사용

document.getElementsByName(name속성의 값)

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>checkbox</title>
<script>
window.onload = function(){
    var hobbyAllBtn = document.getElementById('hobbySelectAllBtn');
    var jobAllBtn = document.getElementById('jobSelectAllBtn');

    var unHobbyAllBtn = document.getElementById('hobbyUnSelectAllBtn');
    var unJobAllBtn = document.getElementById('jobUnSelectAllBtn');

    hobbyAllBtn.addEventListener('click', function(){
        checkedAll('hobby', true);
    });

    jobAllBtn.addEventListener('click', function(){
        checkedAll('job', true);
    });

    unHobbyAllBtn.addEventListener('click', function(){
        checkedAll('hobby', false);
    });

    unJobAllBtn.addEventListener('click', function(){
        checkedAll('job', false);
    });

    function checkedAll(checkType, value){
        for(var i = 0; i < document.getElementsByName(checkType).length; i++){
            document.getElementsByName(checkType)[i].checked = value;
        }
    }
};
</script>
</head>
<body>
    <input type="button" id="hobbySelectAllBtn" value="Select All Hobbies"/>
    <input type="button" id="hobbyUnSelectAllBtn" value="Unselect All Hobbies"/>
    <h3>What's your hobby?</h3>
    <label>listening music<input type="checkbox" name="hobby" value="1"/></label>
    <label>watching youtube<input type="checkbox" name="hobby" value="2"/></label>
    <label>watching movie<input type="checkbox" name="hobby" value="3"/></label>
    <label>making doll<input type="checkbox" name="hobby" value="4"/></label>
    <label>cooking<input type="checkbox" name="hobby" value="5"/></label>
    <label>coding<input type="checkbox" name="hobby" value="6"/></label>
    <label>none<input type="checkbox" name="hobby" value="7"/></label>
    <br>
    <br>
    <br>
    <input type="button" id="jobSelectAllBtn" value="Select All Jobs"/>
    <input type="button" id="jobUnSelectAllBtn" value="Unselect All Jobs"/>
    <h3>What's your Job?</h3>
    <label>business<input type="checkbox" name="job" value="1"/></label>
    <label>operation<input type="checkbox" name="job" value="2"/></label>
    <label>head hunter<input type="checkbox" name="job" value="3"/></label>
    <label>president<input type="checkbox" name="job" value="4"/></label>
    <label>driver<input type="checkbox" name="job" value="5"/></label>
    <label>programmer<input type="checkbox" name="job" value="6"/></label>
    <label>designer<input type="checkbox" name="job" value="7"/></label>
</body>
</html>

복습

 

라디오버튼 체크하기

라디오가 체크된 상태인지 아닌지 알아보는 방법

선택자.checked

라디오버튼을 체크 상태로 만드는 방법

선택자.checked = true;

라디오버튼을 체크 안된 상태로 만드는 방법

선택자.checked = false;

 

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>radiocheck</title>
  6. <script>
  7. window.onload = function(){
  8. document.getElementById('checked').checked = false;
  9. document.getElementById('unchecked').checked = true;
  10. };
  11. </script>
  12. </head>
  13. <body>
  14. <label for="checked">checked</label>
  15. <input type="radio" id="checked" checked/>
  16. <label for="unchecked">unchecked</label>
  17. <input type="radio" id="unchecked" />
  18. </body>
  19. </html>

input태그 업로드 파일명 출력하기

파일 업로드 태그에 선택한 파일의 정보 보기

선택자.files

 

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>다중 파일 입력폼</title>
  6. </head>
  7. <body>
  8. <form name="이 폼의 이름" action="이 데이터들을 받을 파일" method="post" enctype="multipart/form-data">
  9. <input type='file' id="myFile" name='' multiple/>
  10. </form>
  11. </body>
  12. </html>

파일 여러개 등록해보고

console에서 

document.getElementById('myFile').files;

 

2개의 파일 선택

document.getElementById('myFile').files[0].name;

document.getElementById('myFile').files[1].name;

 

파일을 선택하면 선택한 파일명이 출력

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <title>다중 파일 목록</title>
  6. <script>
  7. window.onload = function(){
  8. target = document.getElementById('myFile');
  9. target.addEventListener('change', function(){
  10. fileList = "";
  11. for(i = 0; i < target.files.length; i++){
  12. fileList += target.files[i].name + '<br>';
  13. }
  14. target2 = document.getElementById('showFiles');
  15. target2.innerHTML = fileList;
  16. });
  17. }
  18. </script>
  19. </head>
  20. <body>
  21. <form name="이 폼의 이름" action="이 데이터들을 받을 파일" method="post" enctype="multipart/form-data">
  22. <input type='file' id="myFile" name='' multiple/>
  23. </form>
  24. <div id="showFiles">
  25. </div>
  26. </body>
  27. </html>

타임스태프를 자바스크립트에서 표시할때

 

날짜 객체 생성

var date = new Date();

 

  1. var timestamp = 1476508607 * 1000; //밀리세컨트의 단위를 기준으로 한다.
  2. var date = new Date(timestamp);
  3. console.log('year is ' + date.getFullYear());

자바스크립트를 이용하여 특정 엘리먼트(태그) 이동하기

document.getElementById(엘리먼트이름).scrollIntoView();

 

페이스북 자바스크립트 SDK를 이용하여 자신의 웹페이지에서 페이스북 계정으로 로그인 하기