[JavaScript] 기본 개념

:)·2024년 4월 8일

개발

목록 보기
10/19
post-thumbnail

기본개념

JavaScript Datatypes

  1. String : 문자열 리터럴은 '' 또는 "" 기호 사용
    1. 따옴표 종류가 다르면 같이 쓸 수 있으나 같다면 |' 처럼 역슬래시를 붙여줘야함
      ; 생략가능
  2. Number : 정수 또는 실수
  3. Bigint
  4. Boolean : true, false
  5. Undefined : 자바스크립트 특징. 값이 없는 변수는 undefined(타입,값)
  6. Null
  • Object : 객체.(배열 포함)
    • 객체 정의 기호 : {}
    • 자바: 객체의 구성요소 - 속성과 메소드 → 미리 클래스로 정의 ↔ 자바스크립트: 구성요소를 미리 정의하지않는 프로토타입 기반 객체
      → 구성요소인 속성과 메소드의 추가가 가능
      ```jsx
      -객체 리터럴을 const 변수 sana에 대입 - 객체이름:sana
      - key: value ->map과 유사
      const sana = {name:'사나', age:23, address:'경기'}
      -구성요소가 없는 객체리터럴 선언
      
      const momo= {}
      momo.color = 'red'; 
      
      -객체의 메소드는 함수 리터럴(문자)로 정의
      sana.hello = function(){
      alert(`안녕하세요. 나는 ${this.name}입니다.`)}
      
      ```
    • this 사용 가능 (애로우function에서는 불가능 : 익명객체 형태이기에 .. this는 정의되어있는 것 →메소드 정의할때는 function으로 적기)
    • 배열

Keywords

  • var : 전역 범위, 재정의 가능
  • let : 블록{}범위, 재선언 불가능
  • const : 블록 범위, 상수
  • if
  • switch
  • for
  • function
  • return
  • try

참고

변수 시작문자

  • A letter (A-Z or a-z)
  • A dollar sign ($)
  • Or an underscore (_)

참고


산술 연산

참고

OperatorDescription
+Addition
-Subtraction
*Multiplication
**Exponentiation (ES2016)
/Division
%Modulus (Division Remainder)
++Increment
--Decrement

논술 연산

OperatorDescription
&&logical and
!logical not
  • 주의점 (+와 String) value값을 가져오면 무조건 string → +연산은 주의!
    switch(operator.value){
    case '+':
    // +는 캐스팅안하고 할 수 있는 연산인 문자열 연결을 실행함
    //강제 캐스팅
    temp =Number(op1.value) + Number(op2.value)
    break;
    case '-':
    // 문자열을 연산에 맞게 자동 캐스팅함
    temp = op1.value - op2.value
    break;

대입 연산

OperatorExampleSame As
=x = yx = y
+=x += yx = x + y
-=x -= yx = x - y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y
**=x **= yx = x ** y

비교연산

OperatorDescription
==값 동등 비교
===값과 형식 동등 비교
!=값 불일치 비교
!==not equal value or not equal type
>greater than
<less than
>=greater than or equal to
<=less than or equal to
?ternary operator

타입 연산

  • typeof
  • instanceof

데이터 타입

참고

객체

  1. window 객체 : 브라우저 창에 대한 객체
    메소드 : alert , confirm
    하위 객체 : document , console , history, location 등
    프로퍼티 : innerWidth, innerHeight , screenX, screenY 등
    메소드, 하위객체 등을 사용할 때 window는 생략하고 사용
    1. document 객체 : 웹페이지(문서) 에 대한 객체 참고 : https://www.w3schools.com/jsref/prop_win_document.asp
    1. 하위객체 forms : 웹문서에 포함된 form 객체들을 리턴.
    2. 프로퍼티 URL
    1. 현재 URL 문자열 가져오는 속성. document.URL
    - html , css로 작성된 정적인 웹컨텐츠 → 동적인 기능으로 컨텐츠 조작가능
    - 사용자가 입력한 값을 서버로 보내기 전에 유효한 값인지 검사하거나 버튼 클릭시 무엇을 할것인지에 대한 명령을 작성
    - 브라우저가 실행환경. 개발자도구-콘솔에서 직접 명령어를 하나씩 실행하면서 결과 확인 가능
    2. location.href='https://www.naver.com' -이동
    1. location 객체는 브라우저의 url정보를 저장, href 속성으로 접근 history.back() ->브라우저의 웹페이지 이동에 대한 정보를 저장 window.innerWidth window.innerHeight => 전체 요소 선택한 후 크기값이 일치하는지 확인하기
  • 주요객체, 제일 많이 사용하는 것 - > document
    • ㄴgetElementById(id 값으로 요소를 가져옴
    • ㄴ실행결과 <시작태그> 내용</종료태그> 와 같은 하나의 요소를 가져옴

주요 메소드

  • getElementById: 지정된 id로 요소를 가져오기. 리턴이 단일 요소 (’’)
  • getElementsByClassName: 지정된 class 이름으로 요소들을 가져오기. 리턴이 배열(컬렉션) 형식 다중 요소
  • getElmentsByTagName : 지정된 tag 이름으로 요소들을 가져오기
  • querySelector : 구체적인 그룹과 일치하는 document안 첫번째 엘리먼트 가져옴(단일). css 에서 사용한 선택자 기호 동일하게 작성.
    • 태그의 요소(ex- tbody)로만 적으려면 하나만 있을 경우 가능
      getElementById 대신 css에서 사용했던 선택자로 요소 가져오기-> querySelector 한개만/ querySelectorAll 여러개 가져오는 메소드
      const trOne= document.querySelector('tr')
      console.log(trOne)
      const trMany= document.querySelectorAll('tr')
      console.log(trMany)
      
  • querySelectorAll: 선택자로 가져오기. 여러개 요소 가져오기- 태그이름. 클래스 이름 사용

function

  • 기본은 아직 정의되어 있지 않은 함수는 호출할 수 없음

  • 단, function 함수이름() {}로 정의된 함수(1번)는 함수 끌어올리기라는 걸 함 (hoistiong) → 함수 위에서도 사용 가능

  • 함수 밖에서 값을 선언하면 화면이 만들어지는 순간 만들어지기에 값이 없는 상태로 저장됨-> 값을 담고 싶으면 함수 안에 선언해야함

  • 문법적인 규칙은 2,3번이 주로 쓰임.. 각각의 사용 필요가 있음

  • 인자값 없거나 부족하면 연산 못함 (NaN)

  • action 속성값: 입력값을 받을 서버의 url

  • 빈공간 조건식
    if (name.value == '')

  • 형식

    let result =0;
    result = myfuncA(3,1);
    console.log('@@@ myfuncA 리턴 =', result)
    // result = myfuncB(3,"2")               //오류는 없지만 + 대신 문자열 연결연산합니다.
    // console.log('@@@ myfuncB 리턴 =', result)
    
    // 기본형식 1
    function myfuncA(x,y) { // 인자가 2개
    	let temp = x * 10 + y;   // 샘플 수식
    	console.log("myfuncA 실행하기!!")
    	console.log("리턴값 = "+temp)
    	return temp;  }
    
    // 기본형식 2 - 함수를 값처럼 변수 const에 대입
    const myfuncB = function(x,y){
    	let temp = x * 10 + y;
    	console.log("myfuncA 실행하기!!")
    	console.log("리턴값 = "+temp)
    	return temp;}
    
    // 형식3 - 화살표 함수(arrow function). 메소드의 인자가 함수 일 때 많이 사용
    const myfuncC = (x,y) => {
    	let temp = x * 10 + y;
    	console.log("myfuncA 실행하기!!")
    	console.log("리턴값 = "+temp)
    	return temp;}
  • 선택된 값 저장하기 + 유효성 검사

    function save(){
                const name = document.querySelector('input[name="name"]')
                const age = document.querySelector('input[name="age"]')
                const temp = document.querySelectorAll('input[type="checkbox"]')
                const hobbies = document.querySelectorAll('input[type="checkbox"]:checked')
                console.log(name.value)
                console.log(age.value)
                temp.forEach((ele,i)=> console.log('checkbox',i,'=',ele.value))
                hobbies.forEach((ele,i)=> console.log('checkbox.cheked',i,'=',ele.value))
    
                // 사용자 양식에는 필수 입력 항목이 있음. ->이름 ,나이 .. (유효성 검사)
                //입력값에 대한 검사를 함 -> 함수 안에 넣어서..
                if(name.value ==''){
                    alert('이름을 입력하세요')
                    name.focus() //해당 칸으로 포커스가 감
                    return; //함수 종료
                }
                if(age.value ==''){
                    alert('나이를 입력하세요')
                    age.focus()
                    return; //함수 종료
                }
                let hobbStr =''
                const hobbArr = []
                hobbies.forEach(ele=>{
                    //console.log(ele.value)
                    hobbArr.push(ele.value)
                    console.log(hobbArr)
                })
                hobbStr=hobbArr.join(',') //기호 , 로 배열값들 연결하기(join 메소드는 문자열 리턴)
    
                //alert(`${name.value}님(${age.value})이 선택한 취미는 ${hobbStr}입니다`)
                alert(`${name.value}님(${age.value})이 선택한 취미는 ${hobbArr.join(',')}입니다`)
                alert('입력데이터 저장완료')
            }
  • 제어문: if, switch, for는 자바와 동일하게 사용
  • prompt - 입력창
  • 함수정의(선언) 키워드:function, 리턴값은 return키워드
  • 동적으로 사이트가 변화되게 사용자가 이벤트를 발생시킴 → 이벤트: click, drag drop, change, resize..
    • 태그 요소의 이벤트 속성: onXXXX의 값은자바스크립트 코드 1개 또는 함수

웹문서에서 요소 가져오는 메소드 (자바스크립트에서 매우 중요)

document.getElementById('lblEmail')
document.getElementsByTagName('input') 
document.querySelector('#lblAge') 
document.querySelectorAll('label') 
document.forms document.forms[0] : form 들 중에서 0번 인덱스 가져오기
  • regex - 정규식 (w3schools에서 확인 가능)
    • 정규식을 이용하여 /[]/ 기호 안에 원하는 패턴 작성 []안에는 사용가능한 문자를 나열.

      let regex= /[a-zA-Z가-힣]+/
      let regex= /^[a-zA-Z-]$/    -> ^$는 원래 사용해야하나 생략가능
    • 1번이상 반복가능한 패턴기호는 +(중복입력가능)

    • ? -> ()로 묶여있는 부분 사용 한번 또는 사용 안함

    • 한번이상 사용 가능

      • 기호 대신 {} 안에 문자의 개수를 범위로 지정 {2,5} ->2~5개 / {3} -> 3개 / {2, } 2개 이상 / { , 5} 5개 이하
      • 0개 이상
    • 이름에 대한 유효성 검사: 영문자 또는 한글만 가능 → 정규식 패턴을 이용

      regex.test(name.value) -> 홍길동 true, 홍길동12 false
      if(regex.test(name.value))   참일경우
      if(!regex.test(name.value))  거짓일경우
    • 핸드폰 번호 정규식

      var regPhone = /^01([0|1|6|7|8|9])-?([0-9]{3,4})-?([0-9]{4})$/
      • 01로 시작하고 (0,1,6,7,8,9 중 하나의 문자) -은 있을수도 없을수도 (숫자만 들어가면서 3~4 길이의 문자)
    • 이메일 정규식

      var regEmail = /^[0-9a-zA-Z](notion://www.notion.so/%5B-_%5C.%5D?%5B0-9a-zA-Z%5D)*@[0-9a-zA-Z](notion://www.notion.so/%5B-_%5C.%5D?%5B0-9a-zA-Z%5D)*\.[a-zA-Z]{2,3}$/
      • 숫자나 영어로 시작, - . 포함한 숫자나 영어만 있고, @ , 숫자나 영어로 다시 시작, - . 을 포함한 영어나 숫자만 있고, . , 2개 또는 3개의 글자인 영어로 끝
    • 특수문자 정규식

      let regPw = /[!@#$%^&*(),.?":{}|<>]/;
  • document.write 또는 writeln 메소드 -> 웹문서에 문자열 출력(println과 유사) document.write('
    ') '<태그>' 가능
    document.writeln('
    ') 스타일 지정도 가능
  • html 요소의 내용을 바꾸기 ( 변수 = 값) document.forms[0].age.value = 32 document.forms[0].hobby[3].checked=false document.forms[0].address.value='기타'
  • Button - ON/OFF
    <button id="executeBtn" onclick="calculate()">실행</button>        -> () 주의!!
    • 비활성화 코드

      .disabled
              const bulb = document.getElementById('bulb')
              const on= document.getElementById('on')
              const off= document.getElementById('off')
              off.disabled = true
      
              function bulbon(){
                  bulb.src="../image/KakaoTalk_20240213_160833779.gif"
                  // 요소의 disable 속성을 설정 
                  on.disabled = true      //비활성화
                  off.disabled= false     //활성화
              }
  • Date
    현재날짜와 시간: new Date()
     document.writeln(new Date())
    
    -Locale: 국가 혹은 언어와 관련된 정보(en-US, ko-KR..)
     운영체제에 설정한 현지시간을 현지 형식에 맞게 출력 (03/10/2025 ... )
    document.writeln('toLocaleString = ',new Date().toLocaleString());
    
    document.writeln('toLocaleDateString en = ',new Date().toLocaleDateString('en-US',{year:'numeric',month:"2-digit", day:"2-digit"}));
    document.writeln('toLocaleDateString kr = ',new Date().toLocaleDateString('kr-KR',{year:'numeric',month:"2-digit", day:"2-digit"}));   
    document.writeln('toLocaleDateString zn-CN = ',new Date().toLocaleDateString('zn-CN',{year:'numeric',month:"2-digit", day:"2-digit"}));   
    
    -표준시간 출력
    document.writeln('toUTCString(협정 세계시)= ',new Date().toUTCString());
    document.writeln('toISOString(국제 표준형식)= ',new Date().toISOString());
    
    -날짜 및 시간 GET 메소드</h4>');
    document.writeln('년도 = ',new Date().getFullYear());
    document.writeln('월 = ',new Date().getMonth()+1); //월이 0부터 시작함
    document.writeln('일 = ',new Date().getDate());
    document.writeln('요일 = ',new Date().getDay());//요일 0~6. 0=일요일
    document.writeln('시 = ',new Date().getHours());
    document.writeln('분 = ',new Date().getSeconds());
    document.writeln('초 = ',new Date().getMilliseconds());
    
    -날짜 및 시간 SET 메소드
    setXXX메소드로 today에 저장된 날짜 변경 가능
    
    let today=new Date();
    
    today.setFullYear(today.getFullYear()+3)
    document.writeln('today.getFullYear()+3 = ', today);
    today.setMonth(today.getMonth()+4)
    document.writeln('today.getMonth()+4 = ', today);
    today.setDate(today.getDate()+10)
    document.writeln('today.getDate()+10 = ', today);
    
    -원하는 날짜로 설정
    let mybirth = new Date('2020-11-03')
    • 달력만들기(예제) 1) 18,19번은 입력요소 가져올 때 querySelector 사용 -> 선택자 연습 예제
      2) form은 document의 하위 객체. 여러 form을 가질 수 있으므로 배열 forms 이용하여 입력 요소 값을 가져올 수 있음
      const night = document.forms[0].days //name 속성값사용
      -날짜를 전달하면 yyyy-mm-dd 패턴의 문자열로 리턴해주는 함수
      function Dateformat(vdate){ //vdate->날짜타입 인자
        const year = vdate.getFullYear();
        const month = (vdate.getMonth()+1).toString().padStart(2,'0');   //month는 int, 문자열 수정은 String 일때 가능
        const date = vdate.getDate().toString().padStart(2,'0');         //padStart ->무조건 2자리로. 없으면 0을 채워서
        console.log([year,month,date].join('-'))}                        //[] 배열 값을 기호 -로 연결
      Dateformat(new Date())
      
      1)숙박일수 선택시
      document.getElementById('night').addEventListener('change', changeEndDate)
      
      2) 입실날짜 선택시 
      document.getElementById('enterDate').addEventListener('change', changeEndDate)
      
      function changeEndDate() {
        console.log('선택 숙박일 =', night.value)
        let end_date = new Date(start.value)
        end_date.setDate(end_date.getDate()+Number(night.value))
        end.value = dateFormat(end_date) } // //퇴실날짜 input은 전역변수 end로 선언
             
      
      -입실날짜 요소의 min,max 속성으로 값의 제한을 설정
      -요구사항 min: 오늘날짜 / max : 3개월
      
      function initStart(){
        let today = new Date();
        start.value = dateFormat(today);
        start.min = start.value;                 //오늘날짜 이전 선택 불가
        today.setMonth(today.getMonth()+3)       //3달 이후까지만 선택 가능
        start.max = dateFormat(today)}
      26_dateForm-T.html
  • pre
    <pre style="font-size: 1rem; font-family: inherit;">
    • pre 태그는 코드 출력할 때, 보이는 그대로 출력 (코드의 들여쓰기 포함)
    • 엔터를 줄바꿈 할 목적으로 사용, 스타일이 바뀜... body와 같도록 하려면 style 설정 필요 /inherit:부모스타일 상속

배열

  • 자바와의 차이점: 배열의 크기가 동적 → 자바의 리스트와 JS의 배열이 비슷
  • 인덱스0부터 시작, 배열 요소 접근은 배열이름[인덱스]
  • 주요특징: 메소드가 많음, push()-입력,pop() -제거 ...
  • 정렬
    • 배열의 정렬: times.sort();
    • 문자열 정렬은 사전순 (a-z, 가- 힣, 0 - 9)
    • 객체의 정렬은 기준 속성을 무엇으로 할 것인지 직접 함수로 구현 -> sort 메소드 안에 콜백 함수 사용***
    • js 에서는 문자열도 크다, 작다 기호로 비교 가능
      schedules.sort(function(a,b){
      //비교되는 2개의 a 객체와 b 객체
      
      -비교 속성에 대한 조건식
      -시간 순서로 정렬시
      if(a.time < b.time)
      
      -할일 순서로 정렬시
      if(a.todo < b.todo) 
        return-1
      else  return 1 })
-배열 선언
const names = []; -> 내용이 없는 배열 선언
const arrr=['a',123,new Date()]; // 배열값 형식이 달라도 저장할 수 있음 
//names = ['a','b'] -> 오류.. -> 배열자체를 바꿀 수 없음

-배열로 바꾸기
const liArr = Array.from(lis)    -item은 li 요소

-배열 값 삽입
names.push('사나') //const 배열이 배열 요소 변경은 할 수 있음, 하나씩만 입력 가능
names.push(100) //동일한 배열에 문자열과 number 저장가능
document.write('<h3>names 배열요소</h3>')
document.writeln("names= ",names) //ln은 엔터. 엔터는 html에서는 줄바꿈 안함
const objarr = [momo, sana]; //객체의 구성요소가 다르지만 같은 배열에 저장 가능 (배열[] 과 오브젝트{ } 공존 가능)

-pop
names.pop()  //마지막 인덱스 요소를 제거

-splice: 배열 요소의 삭제 - 위치와 개수 지정
names.splice(3,1) //위치 3, 개수 1
names.splice(3,2) //위치 3, 개수 2

-배열의 크기
document.writeln("names 크기 = ",names.length) 

-요소값 찾기
모모의 위치 찾기
document.writeln(names.indexOf('모모'))
배열에 모모가 있는지
document.writeln('names.includes(\'모모\')=',names.includes('모모'))

콜백 함수(forEach, sort, EventListener, Time, Interval..)

    1. 배열.forEach(함수) : 배열의 요소를 하나씩 가져와서 '함수'를 실행시킴
    • foreach 메소드가 더 많이 쓰임 - 메소드의 인자가 함수->콜백 함수 ***중요
    • names 배열 요소를 순서대로 하나씩 콜백함수 실행시킴
    • 인자 순서 정해져있음: item,index,array
    • 변수명은 상관x →필요없다면 선언안해도 됨
      names.forEach(function(item,index,array){
      document.writeln("item=", item)
      document.writeln("index=", index)
      document.writeln("array=", array)
      })
      
      화살표함수로 변경1
      names.forEach((item) => {
      document.writeln("item=", item)
      })
      
      화살표함수로 변경2
      
      화살 함수를 변수로 선언. 함수 실행코드가 1줄일 경우 {} 생략
      const printItem = (Item) => document.write("Item: ",Item)
      names.forEach(printItem)
      
      item을 매개변수로 삼음..
    1. 배열.sort(함수) : 배열을 정렬할때 정렬 기준과 방법에 동작을 '함수'로 작성
    • 배열의 정렬: times.sort();

      • 문자열 정렬은 사전순 (a-z, 가- 힣, 0 - 9)
      • 객체의 정렬은 기준 속성을 무엇으로 할 것인지 직접 함수로 구현 -sort 메소드 안에 콜백 함수 사용
    • js 에서는 문자열도 크다, 작다 기호로 비교 가능

      schedules.sort(function(a,b)) → 비교되는 2개의 a 객체와 b 객체
      
      --비교 속성에 대한 조건식
      -시간 순서로 정렬시
      if(a.time < b.time) return-1
      else  return 1 })
      
      -할일 순서로 정렬시
      if(a.todo < b.todo) return-1
      else  return 1 })
    1. 요소.addEventListener('click', 함수): 요소가 클릭 이벤트가 생기는지 리슨하고, 이벤트 발생시 '함수'실행
    • addEventListener: 이벤트 핸들러 메소드
      -이벤트 처리방법 1
      <button id="hello" onclick="hello()">Hello</button>
      
      function hello(){
       alert("hello")
       console.log('클릭 이벤트에 대한 함수입니다 button 태그에 hello() 함수 호출 명령이 있습니다.')}
      
      -이벤트 처리방법 2 / 서로의 영역을 침범하지 않고 처리 가능
      <button id="hi">하이</button>
      <pre style="font-size: 1rem; font-family: inherit;">
      
      document.getElementById('hi').addEventListener('click',
       function(){
        alert('하이')
        console.log('button 태그에 자바스크립트 코드를 작성하지 않고 이벤트 처리합니다')})
      
      -2-1 addEventListener의 종류 (change, click, keyup, keydown..)
        1) change: 요소의 값이 변경될 때 발생하는 이벤트 , input에서는 내용이 바뀌는 이벤트
        2) click: 마우스 input을 클릭시 발생하는 이벤트
           document.getElementById('message').addEventListener('change',()=>{
           const msg = document.getElementById('message')
           console.log(msg.value)})
      
        3) keyup->눌렀다 뗄때(aaaaaaa ....), 
        4) keydown->입력(누를떄 - a) -> 비슷함
           document.getElementById('message').addEventListener('keyup',()=>{
           const msg = document.getElementById('message')
           console.log(msg.value) })
      
    • 이벤트 타겟 : 큰 범위로 작은 내용들까지 감쌈
      • span 클릭하면 alert을 띄우고 싶음
        1. span에 이벤트 주기 - click 이벤트 핸들러 작성 → 단 span 5개에 모두 동일한 작업 필요
        2. div에 이벤트 주기(dom구조인 html은 이벤트를 상속함)
      • 콜백 함수의 인자 e는 이벤트를 발생시킨 정보를 포함
        document.getElementById('container').addEventListener('click',function(e){
            console.log(e)
            console.log('e.target.tagName=', e.target.tagName)
            if(e.target.tagName==='SPAN'){
            //alert(`선택한 공은 ${e.target.outerText}입니다.`)
            alert(`선택한 공은 ${e.target.innerHTML}입니다.`)}})
  1. setInterval(시간, 함수): 정해진 시간마다 함수 실행(여러번 실행)
    setTimeout(시간, 함수) : 정해진 시간이 지나면 함수 실행(1번 실행)
  • 콜백함수 이름을 인자로 전달시에는 ()안씀 - 호출임

Form

  • forms 객체로 가져올 때는 name 속성을 활용
    document.forms[0].age : 지정된 form에서 name 속성 age 가져오기 
    document.forms[0].age.value : 가져온 input 요소의 value document.forms[0].name.value
  • form 의 checkbox 요소: 배열
    document.forms[0].hobby 
    document.forms[0].hobby[0].value => 요소 인덱스 지정해야 value 를 알 수 있음
    document.forms[0].hobby[1].value 
    document.forms[0].hobby[2].value 
    document.forms[0].hobby.value => '' 비교: radio 버튼 
    document.forms[0].gender => 요소들 배열 
    document.forms[0].gender.value => 선택한 값 리턴
  • submit
    • required나 email 타입 체크는 태그에 설정한 것으로 submit되기 전에 동작, onsubmit 함수 실행 전에 동작

      <input type="text" name="name" id="" placeholder="이름을 입력하세요" required>
    • submit

      181. form: 입력데이터 서버로 전송하기- onsubmit 활용(버튼은 submit동작)
          <!-- 17번 파일에서 form 태그 사용이 추가됨 -> 버튼의 동작이 submit이 됨 -->
          <!-- action 속성값: 입력값을 받을 서버의 url -->
          <!-- onsubmit 속성: submit 이벤트 발생시 실행할 js 코드(혹은 함수) 
                              함수 returnfalse이면 action으로 넘어가지 않음 ->false로 만들어서 넘어가지 못하도록 만들기 가능-->
      --
      
      192. form: 입력데이터 서버로 전송하기2 - 자바스크립트에서 submit()메소드 활용 (버튼은 일반 button 동작)
      <!-- button의 타입을 button으로 해서 동작시킬수도 있음 -->
          <form action="../day3_form/success.html">
      <button type="button" onclick="save()">저장하기</button>
      
      if (age.value == '') {
        alert('나이를 입력하세요');
        age.focus();
        isValid= false;}
      
      if(isValid){  //, 유효성 검사가 모두 끝나고 isValid가 참일때만 form 제출
        const hobbArr = []     
        hobbies.forEach(ele => {
          hobbArr.push(ele.value)
          console.log(hobbArr)})
        alert(`${name.value}님(${age.value}) 선택한 취미는 ${hobbArr.join(',')} 입니다.`)
        alert('입력 데이터 저장완료!!')
      document.forms[0].submit();// 직접 submit동작 메소드}
    • required : 필수 입력 (submit일때만 동작)

    • 기본 type= submit. 클릭하면 action에 저장된 url로 전송

      • form method="get" 이면 파라미터가 url에 포함됨 (default) ->조회목적 “post” - 가려
    • input type="email" -> text 타입과 같음.. + @를 확인하는 기능 포함

      • password→ 자동으로 문자를 가려줌
  • 가상요소 선택자: ::marker, ::before, ::after
    <fieldset> 
    	<legend>취미를 선택하세요</legend> 
    	<input type="checkbox" name="hobby" id="swimming" value="수영"> 
    	<label for = "swimming">수영</label>
    	<input type="checkbox" name="hobby" id="ski" value="스키">
    	<label for = "ski">스키</label> 
    	<input type="checkbox" name="hobby" id="football" value="축구"> 
    	<label for = "football">축구</label> 
    	<input type="checkbox" name="hobby" id="baseball" value="야구"> 
    	<label for = "baseball">야구</label> 
    	<input type="checkbox" name="hobby" id="running" value="달리기"> 
    	<label for = "running">달리기</label> 
    </fieldset> ->

  • 문제 : 맨위의 '회원가입'제목 요소를 가져오려면?
    document.getElementsByTagName('h3') => 기본이 컬렉션(배열)을 리턴하는 메소드 
    document.querySelector('h3') => h3태그가 문서에 1개 있을 때만 querySelector 사용 
    document.querySelector('h3').innerHTML => h3태그의 콘텐츠(텍스트)
    -요소의 style 변경이 가능. 
    document.querySelector('h3').style.color = 'blue' document.querySelector('h3').style.border = '1px solid gray'
  • lis는
  • 요소의 집합. 배열이 아닌 collection → foreach 를 실행하려면 배열로 변환해야함
  • 요소 식별 → id (유일성) - #id / class (중복 가능) - . class
  • , + 등 연결 기호 다양하게 사용 가능

  • SPA(single-page application, 스파)
    • 서버로부터 완전한 새로운 페이지를 불러오지 않고 현재의 페이지를 동적으로 다시 작성함으로써 사용자와 소통하는 웹 애플리케이션이나 웹사이트
    • 하나의 html안에서 내용이나 style을 바꾸는 것 (최근 트렌드)

템플릿 리터럴(멀티라인, 표현식) :

  • (백틱``) 기호 사용은 ${} 을 사용하기 위한 기호
  • 변수 또는 수식 표현식을 ${} 기호에 표시
    document.writeln([${item}])
    document.writeln('['+item+']')
profile
:) GITHUB: https://github.com/YJ2123412

0개의 댓글