본문 바로가기

Web Development/SIST

[JS] 8주차 수업: 2024.04.08 - 2024.04.12

2024.04.08

*instanceof

-해당 객체가 어떤 함수를 통해 생성됐는지 확인할 때 instanceof 키워드를 사용
-객체가 속한 클래스와 상위 클래스 체크

-자바와는 달리 instanceof 뒤의 클래스가 객체의 상위 클래스가 아니더라도 예외를 발생시키지 않고 false를 반환함

document.write(student instanceof Student); //true
document.write('<br>');
document.write(student instanceof Object); //true
document.write('<br>');
document.write(student instanceof Number); //false

 

*클라이언트 객체(내장 객체)

객체 특징
window 최상위 객체로 자바스크립트에서 사용되는 모든 객체를 처리
navigator 웹 브라우저에 관련된 정보를 제공
link 하이퍼링크와 관련된 작업 처리
anchor 특정 위치로의 이동 객체
image 문서 내의 그림에 관련된 처리
location 현재 문서의 URL과 관련된 정보를 처리
history 방문기록에 관련된 처리
document 문서에 대한 정보를 처리
form 폼에 있는 양식 객체를 처리

 

-클라이언트 객체 계층도

 

*window 메서드

-window.alert() : 경고창
-window.prompt() : 입력창
-window.confirm() : 선택창. 확인을 누르면 true, 취소를 누르면 false

 

-window는 생략하고 사용 가능

window.alert('경고창'); // =alert('경고창')

 

 

*window.open(url, 새창 이름, 옵션): 창 열기

옵션

-width : 새 윈도우의 넓이
-height : 새 윈도우의 높이
-location : 주소 입력창 유무
-menubar : 메뉴의 유무
-resizable : 화면 크기 조절 가능 여부
-status : 상태 표시줄의 유무
-toolbar : 툴바 유무
-scrollbars : 스크롤바 유무
-left : 창의 가로축 위치 지정
-top : 창의 세로축 위치 지정

    let win;
  function winOpen() {
    win = window.open(
      "https://www.naver.com",
      "child",
      "toolbar=no,location=no,status=no,menubar=no,resizable=no,scrollbars=no,width=400,height=300"
    );
  }

  function winClose() {
    //새로 열린 창 닫기
    win.close();
  }
</script>

<input type="button" value="창 열기" onclick="winOpen();" />
<input type="button" value="창 닫기" onclick="winClose();" />

 

-window.onload = function() {}

:윈도우가 로드될 때 함수 실행

 

-setTimeout(function, millisecond) : 일정 시간 후에 함수를 한 번 실행

  window.onload = function () {
    alert('경고창을 닫고 3초 후 이 페이지는 종료됩니다.');
    window.setTimeout(function(){
        window.close(); //현재 창을 닫음
    }, 3000);
  };

 

*window.location을 이용한 페이지 이동

<input
  type="button"
  value="이동(href)"
  onclick="location.href='s01_window.html'"
/>
<input
  type="button"
  value="이동(assign)"
  onclick="location.assign('s02_window.html')"
/>
<input
  type="button"
  value="이동(replace)"
  onclick="location.replace('s02_window.html')" 
/>

-location.replace() : 페이지 이동을 할 수 있고 이동시 history 정보가 지워짐

 

-location.reload() : 새로고침

<input type="button" value="새로고침" onclick="location.reload()" />

 

 

*history

-history.back() : 이전 페이지로 이동

-history.go(음수) : 이전 페이지로 이동

<input type="button" value="이전(back)" onclick="history.back();" />
<input type="button" value="이전(go(-1))" onclick="history.go(-1);" /> <!--음수-->

전 페이지가 있을 경우에만 동작

 

-history.forward() : 다음 페이지로 이동

-history.go(양수) : 다음 페이지로 이동

<input type="button" value="다음(forward)" onclick="history.forward();" />
<input type="button" value="다음(go(1))" onclick="history.go(1);" /> <!--양수-->

다음 페이지가 있을 경우에만 동작

 

*내장 객체

-메서드를 넣어서 사용하기 위해서 내장 객체를 사용

 

*Array

-메서드는 기본 자료형과 동일하나 생성자 함수를 사용해서 생성해야함

-배열 생성

const array1 = new Array(); //빈 배열
const array2 = new Array(10); //배열의 길이를 10으로 지정

 

-배열 생성 및 초기값 지정

const array3 = new Array(52,273,103,57,32);

 

*String

-문자열을 생성할 때는 기존과 같이 변수를 만들어서 대입함

-dom을 사용하여 input 요소에 접근 (name 속성을 통해)

<body>
<script>
  function trans() {
    //input 태그에 입력한 값 반환
    let txt = document.form1.id.value; //document는 전체 html문서

    txt = txt.toUpperCase(); //대문자로 변환 후 반환

    //대문자로 변환된 데이터를 input 태그에 표시
    document.form1.id.value = txt;
  }
</script>

<form name="form1">
  ID를 소문자로 입력하세요. 대문자로 변환됩니다.<br />
  ID : <input type="text" name="id" />
  <input type="button" value="입력" onclick="trans()" />
</form>
</body>

 

*문자열 자르기

-string.substr(start, length) : 시작 인덱스, 추출할 문자 개수

-string.substring(start, end) : 시작 인덱스부터 끝 인덱스 전까지

-string.slice(start, end) : 시작 인덱스부터 끝 인덱스 전까지

 

*Date

-자바의 Calendar/Date 객체가 합쳐진 형태

-현재 날짜/시각 객체 생성

const now = new Date();

 

-날짜/시각 읽어오기

document.write('now.toString(): ' + now.toString() + '<br>');
//로컬언어로 읽어오기
document.write('오늘: ' + now.toLocaleString() + '<br>');

 

-오늘 날짜, 시각 각각 로컬언어로 읽어오기

document.write("오늘의 날짜: " + now.toLocaleDateString() + "<br>");
document.write("지금 시각: " + now.toLocaleTimeString() + "<br>");

 

-연-월-일-요일-시-분-초-밀리초 읽어오기

//연
document.write('연도: ' + now.getFullYear() + '<br>');
//월 : 0~11로 반환
document.write('월: ' + (now.getMonth()+1) + '<br>');
//일
document.write('일: ' + now.getDate() + '<br>');
//요일: 0(일)~6(토)
document.write('요일: ' + now.getDay() + '<br>');
//시: 0~23
document.write('시: ' + now.getHours() + '<br>');
document.write("분: " + now.getMinutes() + "<br>");
document.write("초: " + now.getSeconds() + "<br>");
document.write("밀리초: " + now.getMilliseconds() + "<br>");

 

*윈도우가 다 로드된 후 스크립트가 실행되게 하기

<script>
    window.onload = function() {};
</script>

 

*id를 통해 태그에 접근하기

document.getElementById('display').innerHTML = clock;

 

*Number

-toFixed(소수자리수): 자리수를 지정해서 인자로 받은 자리수까지 반올림

document.write('소수점 셋째자리에서 반올림 : ' + newNum.toFixed(2) + '<br>'); //12254.44

 

-toLocaleString(): 숫자/날짜에 로컬 포맷 주기

->숫자 세 자리 콤마 지정 (디폴트 반올림해서 소수점 셋째자리까지 출력)

document.write(number.toLocaleString() + '<br>'); //1,234,567.494

 

-소수점자리 옵션

//지정된 지역에서 사용하는 숫자의 표현방식으로 문자열 반환
document.write(number.toLocaleString(undefined, {maximumFractionDigits:5}));
                                      //locale, 옵션

 

 

DOM

*getElementsByTagName("태그명")

-태그이름으로 요소 반환

-결과가 배열로 생성됨

 

*getElementById("아이디")

-요소의 아이디로 요소 반환

-아이디는 유니크해야함

 

*getElementsByName("name 속성")

-name 속성으로 요소 반환

-결과가 배열로 생성됨

 

 

2024.04.09

*getElementsByClassName("클래스명")

-요소의 클래스명으로 요소 반환

-결과가 배열로 생성됨

-클래스명이 여러개가 모두 일치하는 요소를 반환하고 싶을 경우 공백을 구분자로 해서 문자열로 전달(순서는 변경 가능)

//태그 중에서 class명이 matched와 unmatched 모두 적용된 태그를 반환
//클래스명이 여러개일 경우 공백을 구분자로 해서 문자열로 전달
//순서는 변경 가능
const fooMatched2 = foo2.getElementsByClassName('matched unmatched');

 

*querySelector('CSS선택자')

-명시한 CSS선택자를 통해 해당 선택자를 사용하는 태그를 반환

-단일한 요소를 반환하기 때문에 id선택자처럼 유니크한 선택자를 넣어주어야 함

let header1 = document.querySelector("#header_1");
let input1 = document.querySelector("#my_form #input_1");

-CSS 선택자에 여러개의 요소가 해당되는 상황에서도 그 중 첫번째 요소만을 반환함

 

*querySelectorAll('CSS선택자')

-복수의 요소를 반환하고 싶을 때는 querySelectorAll() 사용

-CSS 선택자에 해당하는 요소를 모두 탐색하여 배열로 반환

const fruits = document.querySelectorAll("ul > li");

 

*태그 생성 - createElement('태그명')

-createElement('태그명')

: 태그 생성

const header = document.createElement("h1"); //h1태그 생성

 

-createTextNode('텍스트 내용')

: 텍스트 생성

const textNode = document.createTextNode("Hello DOM"); //텍스트 생성

 

-element.appendChild(노드)

: 노드를 DOM내의 엘리먼트와 연결

//노드 연결
header.appendChild(textNode); //h1태그에 텍스트를 추가
document.body.appendChild(header); //body에 h1 추가

 

*태그 생성 -innerHTML

-HTML 태그를 포함한 문자열을 만들어 innerHTML 속성에 할당하여 태그 여러개를 한번에 생성

let output = "";
output += "<ul>";
output += " <li>JavaScript</li>";
output += " <li>jQuery</li>";
output += " <li>Ajax</li>";
output += "</ul>";

document.body.innerHTML = output;

 

*태그 제거 (removeChild)

-document.body.removeChild(제거할 객체 변수);

const willRemove = document.getElementById("will_remove");

//3초 후에 매개변수로 전달된 함수를 호출
setTimeout(function () {
    //id가 will_remove인 h1 태그 제거
  document.body.removeChild(willRemove);
}, 3000);

 

*문서 객체의 하위 요소를 모두 제거 (innerHTML)

-document.body.innerHTML = "";

document.body.innerHTML = "";

 

*객체 스타일 변경

-자바스크립트는 식별자에 '-'을 사용할 수 없음

-> css background-color 속성은 javacsript 에서는 backgroundColor 로 명시해야 함.

header.style.border = "2px solid black";
header.style.color = "orange";
header.style.fontFamily = "Helvetica";
header.style.backgroundColor = "olive";

 

 

이벤트 처리

*인라인 이벤트 처리

-코드가 길어지기 때문에 권장하지 않음

<input type="button" value="이동" onclick="location.href='https://www.naver.com'" />
<input type="button" value="확인" onclick="alert('클릭');alert('CLICK')" />

 

*인라인 이벤트 처리 (함수 이용)

-인라인에 바로 명시하는 것보다는 낫지만 약간 옛날 방식

<head>
<style>
  div#header {
    background-color: orange;
  }
</style>
<script>
  function whenClick() {
    alert("CLICK");
  }
</script>
</head>
<body>
<div id="header" onclick="whenClick()">클릭</div>
</body>

 

-name을 통해 요소에 접근하면 DOM에서 계층적으로 접근 가능

let korean = document.myForm.korean.value;
let english = document.myForm.english.value;
let math = document.myForm.math.value;

 

*스크립트 태그에서 이벤트 속성에 이벤트 핸들러를 대입하여 이벤트 정의

<script>
  window.onload = function () {
    const header = document.getElementById("header");

    //이벤트 핸들러
    function whenClick() {
      alert("CLICK!");
    }

    //이벤트 연결
    header.onclick = whenClick; //소괄호를 넣지 않도록 주의
    
    //이벤트 연결을 하는 것이 아니라 함수가 1회 호출되고 이벤트 발생시 함수 호출이 되지 않음
    //header.onclick = whenClick();
  };
</script>
</head>
<body>
	<div id="header">클릭</div>
</body>

 

*onmouseover

-커서를 태그에 올려놓을 때 이벤트 발생

 

*onmouseout

-커서가 태그를 벗어날 때 이벤트 발생

  window.onload = function () {
    const menu = document.getElementsByTagName("li");

    //이벤트 연결
    for (let i = 0; i < menu.length; i++) {
      //커서를 태그에 올려놓을 때 이벤트 발생
      menu[i].onmouseover = function () {
      	//this : 이벤트가 발생한 태그
        this.style.background = "#ff0000";
      };

      //커서가 태그를 벗어날 때 이벤트 발생
      menu[i].onmouseout = function () {
        this.style.background = "#ff8888";
      };
    }
  };

-이벤트 핸들러 안의 this는 이벤트가 발생한 태그를 가리킴

 

-a태그 클릭 안되게 하기

 :a태그의 기본 이벤트 제거

  alink[i].onclick = function() {
    return false;
  }

 

*키 이벤트

이벤트 이름 설명 발생 순서
keydown 키보드가 눌러질 때 발생 1
keypress 글자가 입력될 때 발생(한글로 사용할 수 없음) 2
keyup 키보드가 떼어질 때(주로 이걸로 한글 처리) 3

 

*isNaN을 활용한 조건 체크

-조건을 만족하지 못했을 때는 return하여 함수를 빠져나가게 해주어야 함

  window.onload = function () {
    const btn = document.getElementById("check_age");

    btn.onclick = function () {
      const age = document.getElementById("age");

      //공백 제거를 위해 trim 메서드를 사용함
      if (age.value.trim() == "") {
        alert("나이를 입력하세요");
        age.value = ""; //공백이 있다면 공백을 제거
        age.focus();
        return;
      }
      if (isNaN(age.value)) {
        //숫자가 아닌 경우
        alert("숫자만 입력 가능합니다.");
        age.value = "";
        age.focus();
        return;
      }

      alert("나이는 " + age.value.trim() + "살입니다.");
    };
  };

 

*서버로 form 전송하기

-이벤트는 submit 버튼이 아니라 form에서 발생함

-유효성 검사에서 값이 유효하지 않을 때는 submit이 일어나지 않게 하기 위해 return이 아니라 return false를 

 onsubmit에 전달해야 함.

 

 

2024.04.11

-form의 input 태그의 name 속성은 주로 서버프로그램에서, id는 주로 CSS, JS에서 사용

 

*기본이벤트 제거

명시적 이벤트 연결을 한 다음 return false를 해주어야 함.

  alert("이벤트 연결");
  //기본 이벤트 제거
  return false;

 

*이벤트 전파(전달)

-이벤트 버블링: 자식 노드에서 부모 노드 순으로 이벤트를 실행하는 것을 의미
-이벤트 캡처링: 부모 노드에서 자식 노드 순으로 이벤트를 실행하는 것을 의미 (이제 지원되지 않음)

 

*이벤트 전달 막기

-event 객체를 매개변수로 받아와서 사용(자식 노드에서)

-event.stopPropagation()

document.getElementById("paragraph").onclick = function (event) {
  alert("paragraph");
  this.style.background = "yellow";
  //이벤트 전파 막기
  event.stopPropagation();
};

 

*DOM Level 2 표준 이벤트 모델

-고전 이벤트 모델(기존에 쓰던 것)과 혼재되어 있음
-addEventListener(eventType, eventHandler, useCapture) //capture는 브라우저에서 지원되지 않음 : 이벤트 연결 
-removeEventListener(eventType, eventHandler) : 이벤트 제거

  <script>
    //윈도우가 로드될 때 매개변수로 전달된 함수를 실행
    window.addEventListener("load", function () {
        const header = document.getElementById("header");
        //이벤트 연결
        header.addEventListener(
          "click", function () {
            alert("이벤트 연결");
          }, false
        );
      }, false
    );
  </script>

 

*클래스

-자바스크립트에서도 자바의 영향으로 클래스로 객체 생성 가능

  class Person {
    //클래스 필드
    name = "Smith";
    //메서드
    getName = function () {
      return this.name;
    };
  }

 

-생성자 사용

  //클래스 정의
  class Person {
    //생성자
    constructor(name) {
      //인스턴스 프로퍼티
      this.name = name;
    }
    //메서드
    sayHi() {
      document.write("Hi my name is " + this.name);
    }
  }

 

-스태틱 메서드

    //정적 메서드
    static sayHello() {
      document.write("Hello!!!!!");
    }

 

-스태틱 메서드 호출

Person.sayHello();

 

-상속(자바와 동일한 방식으로 extends 사용)

  //부모 클래스 정의
  class Animal {
    constructor(age, weight) {
      this.age = age;
      this.weight = weight;
    }

    //메서드
    eat() {
      return "eat!";
    }
    move() {
      return "move!";
    }
  }

  //자식 클래스 정의(상속)
  class Bird extends Animal {
    fly() {
      return "fly";
    }
  }

  //자식 객체 생성
  const bird = new Bird(1, 5);
  document.write(bird.age + "<br>");
  document.write(bird.weight + "<br>");
  document.write(bird.eat() + "<br>");
  document.write(bird.move() + "<br>");
  document.write(bird.fly());

 

-자바스크립트에서는 중괄호, 생성자함수, 클래스 형태로 객체 생성 가능

 

*예외처리

-자바스크립트에서 예외처리는 선택사항

-사용자 정의 예외 던지기

  try {
    let result = 10 / 0;

    if (!isFinite(result)) {
      //수를 0으로 나눌 때
      //예외를 일부러 발생시킴
      throw "DivideByZeroException";
    }
  } catch (exception) {
    document.write(exception);
    console.dir(exception);
  }

 

-finally 블럭은 오류가 있거나 또는 없어도 반드시 수행

 

 

2024.04.12

*정규표현식

-정규표현식(regular expression)은 일정한 패턴을 가진 문자열의 집합을 표현하기 위해 사용하는 형식 언어(formal language)

 /패턴/ -> /(시작) 패턴 /(끝)
 ^ 패턴의 시작
 \d 숫자
 {3} 3번 반복
 $ 패턴의 끝

 

-//안의 패턴을 객체로 인식

-정규표현식.test(문자열) : 정규표현식이 매개변수로 전달된 문자열과 패턴 일치하면 true, 불일치하면 false

  //test(문자열) : 정규표현식이 매개변수로 전달된 문자열과 패턴 일치하면 true, 불일치하면 false
  if (!/^\d{3}-\d{4}-\d{4}$/.test(phone.value)) {
    alert("000-0000-0000 형식으로 입력하세요!");
    phone.value = "";
    phone.focus();
    return false;
  }

 

 [] '['와 ']' 사이의 문자들과 매치라는 의미
 [] 안의 문자 사이에 하이픈(-)을 사용하게 되면 문자 사이의 범위(From-To)를 의미
 [0-9] -> [0123456789]와 같은 의미

 

-문자열.match(정규표현식): test보다 느림. 일치하면 검색 데이터를 반환, 불일치하면 null 반환

 

-메타문자

메타문자 의미
. 개행 문자를 제외한 문자 1자 
\s 공백 문자(공백문자는 공백, 탭, 줄바꿈, 리턴키 값 포함)
\S 공백 문자 아님
\w 아무 단어(숫자 포함)
\W 아무 단어 아님
\d 숫자
\D 숫자 이외의 문자
^ 행의 시작, 문자열의 시작(패턴의 시작, 이 문자만 패턴의 앞에 올 수 있음)
$ 행 꼬리, 문자열의 종료(이 문자는패턴의 끝을 알림, 문자열에서 패턴의 마지막 문자는 반드시 이 문자로 끝나야 함)
X? X의 0문자 또는 1문자
X* X의 0문자 이상 반복
X+ X의 1문자 이상 반복
X{n} X의 n회 반복
X{n,} X의 n회 이상 반복
X{n,m} X의 n부터 m회 반복
X|Y X또는 Y
[XYZ] X또는 Y 또는 Z의 1문자(문자의 집합을 나타냄)
[^XYZ] X도 Y도 Z도 아닌 1문자(문자의 집합을 나타냄)

 

*로컬 스토리지

-브라우저를 통해 사용자의 컴퓨터에 데이터를 지속적으로 저장할 수 있는 공간.
-다시 사이트를 방문했을 때 로컬 스토리지에 저장된 모든 데이터를 사용 가능

 

-로컬 스토리지에 데이터 저장

localStorage.setItem("name", text.value);
localStorage.name = text.value;

 

-로컬 스토리지 객체에 저장된 이름 읽기

let loadedName = localStorage.getItem("name");
let loadedName = localStorage.name;

 

*JSON(JavaScript Object Notation)

-자바스크립트를 객체 형식으로 만드는 것

 

*세션 스토리지

-브라우저가 열려있는 동안 데이터를 기억하고 있다가 탭(또는 창)을 닫으면 모두 지워지는 저장 공간

-각 창은 자체적인 개별 세션 스토리지 객체를 가지며, 따라서 데이터를 별도로 유지

-사용자가 특정 사이트에 접속해서 사용자 세션이 지속되는 동안만 지속

 

-세션 스토리지에 데이터 저장

sessionStorage.setItem("name", first.value);
sessionStorage.name = first.value;

 

-세션 스토리지 객체에 저장된 이름 읽기

let loadedName = sessionStorage.getItem("name");
let loadedName = sessionStorage.name;

 

*파일 API

-FileList : 파일 리스트
-File : 파일 데이터
-FileReader : 파일 읽기
-Blob : 바이트 데이터

 

-파일 인풋 받기

<input type="file" id="file" accept="text/*" />

-accept="text/*" 옵션은 파일피커에서 모든 종류의 텍스트 문서를 검색하라는 뜻

 

-input 태그에 multiple 속성을 넣으면 복수의 파일 선택 가능

-파일을 여러개 업로드할 수 있기 때문에 multiple 속성을 명시하는지와 관계 없이 파일 객체는 무조건 배열로 반환됨

//선택한 파일의 file 객체 반환
const file = this.files[0];

 

-파일 내용 읽어오기

const reader = new FileReader(); //파일 읽기 기능 제공
reader.readAsText(file, encoding); //선택한 파일을 읽어서 문자열로 저장
//파일의 내용을 모두 읽어들이면 onload 속성에서 대입된 함수가 호출됨
reader.onload = function () {
  document.getElementById("contents").value = reader.result;
};
//에러 핸들링
reader.onerror = function () {
  alert("파일 읽기 중 오류 발생");
  return;
};