본문 바로가기
카테고리 없음

24. 07. 11 개발자교육 3주차 목요일 함수, DOM탐색, 요소생성, 추가, 제거, 색변경, 합계구하기 ㅠㅠ

by 융기융 2024. 7. 11.
반응형

15_함수

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>15_함수</title>
</head>
<body>
 
  <h1>함수(Function === 기능)</h1>

  <pre>

    - 목표하는 결과를 만들기 위한 코드의 묶음

    - 코드를 {} (블록)으로 묶어서 작성하고
      붙혀진 이름을 호출해서 사용

      [함수 기본 사용법]

      // []  : 생략 가능
      // ... : n개 작성 가능(여러 개)

      funcition 함수명 ([매개변수,...]) // 함수 선언
     
      {
        // 함수 정의        
      }

      함수명 ( [전달인자], ... ); // 함수 호출
  </pre>

  <hr>
  <h1>매개 변수(Parameter), 전달 인자(Argument)</h1>

  <pre>
    * 매개 변수(Parameter)
      - 함수 선언 시 () 안에 작성되는 변수

      - 함수를 호출 할 때 전달되는 값(전달 인자)를
        저장하기 위한 변수

      - 매개 변수는 함수의 지역 변수로 사용됨

    * 전달 인자(Argument)
      - "함수 호출" 시 () 안에 작성되는 값
      - 작성된 값을 함수의 매개 변수로 전달됨
  </pre>  

  <input type="number" id="input1">
  <button id="btn1">매개 변수, 전달 인자 확인</button>

  <hr>

  입력 1 : <input type="number" class="input2"> <br>
  입력 2 : <input type="number" class="input2"> <br>
  입력 3 : <input type="number" class="input2"> <br><br>
           <button id="btn2">합계 구하기</button>
           
           <button id="btn3">합계 구하기(배열 버전)</button>
         
  <hr><hr>

  <h1>return (반환)</h1>

  <pre>
    - 함수 내에 작성하는 명령어

    - 현재 수행 중인 함수를 종료하고
      호출한 곳으로 돌아가라!

    - return;    -> 함수 종료, 호출한 곳으로 돌아감

    - return 값; -> 함수종료, 호출한 곳으로 값을 가지고 돌아감

    (참고)
    함수 정의 시 return을 작성하지 않으면
    코드 해석 시 자동으로 함수 끝에 return 구문이 추가된다.
  </pre>

  <button id="btn4">return 확인하기1</button>

  <button id="btn5">return 확인하기2</button>

  <hr><hr><hr>

  <h1>익명 함수(이름이 없는 함수)</h1>

  <pre>
    [작성법]

    function ([매개변수]){ // 함수 선언

      // 함수 정의

    }

    - 이름이 없는 함수 형태(익명함수)

    - 이름(함수명)이 존재하지 않아서
      필요한 곳에서 별도 호출 불가

    * 익명 함수는 정의 되자 마자 실행
      또는
      변수에 대입, 매개변수, 이벤트 핸들러
      같은 곳에서 사용됨
  </pre>

  <button id="btn6">익명 함수 확인</button>

  <button id="btn7">매개 변수/return 익명 함수 전달하기</button>

  <hr>

  <h1 style="color:red">화살표 함수(Arrow Function)</h1>

  <pre>
    - 익명 함수의 한 종류
    - 익명 함수를 간단히 표기하는 방법 (ES6)

    익명 함수 :  function(){}


    1. 기본 형태 :  () => {}


    <!-- 매개변수 1개면 () 생략 가능!! -->
    2. 매개변수 1개 :  (e) => {}  또는  
                        e  => {}  // () 생략


    3. 매개변수 n개 :  (a,b,c) => {}   //  () 생략 불가


    4. 함수 정의 부분에 return 한 줄만 있을 경우 :

      1) 익명 함수 :               function(){ return 1 + 2; }

      2) 화살표 함수(기본) :       () => { return 1 + 2; }
       
      3) 화살표 함수(return 한줄) : () => 1 + 2
                                    // {return} 생략


    5. 함수 정의 부분에 return 한 줄만 있는데
      return하는 값이 object(객체, 배열 등) 인 경우
      {return} 생략 불가!!!

      () => { return {name:"홍길동", age:20}; }

  </pre>

  <button class="arrow">화살표 함수 기본 형태</button>
  <br>
  <button class="arrow">매개 변수가 1개인 경우</button>
  <br>
  <button class="arrow">한 줄만 작성된 경우</button>
  <br>
  <button class="arrow">object를 return하는 경우</button>

  <br>
  <h1>즉시 실행 함수</h1>

  <pre>
    - 익명 함수가 정의되자마자 실행하게 하는 함수

    [작성법]
        (() => {})()
    함수 정의  함수 실행

    -사용 이유
    1) 성능(속도)적 우위를 가지기 위해서

    2) 변수명 중복 문제 해결 (함수 내 변수 == 지역 변수)
  </pre>




  <!-- 점심메뉴 정하기 -->
  <hr>
  <br>
  <br>
  <br>
  <input type="number" class="ip"><br>
  <button class="lunch" onclick="lunch()">점심메뉴</button>
 

    <script src="../Js/15_함수.js"></script>
</body>
</html>

Javascript

/* 매개 변수(Parameter), 전달 인자(Argument) */
const input1 = document.querySelector("#input1");
const btn1 = document.querySelector("#btn1");

// 전달 받은 값이 양수/음수/0 인지 구분해서 출력하는 함수
function testFn1( num ){

  let str;
  if(num === 0)   str = "0";
  else if(num >0) str = "양수";
  else            str = "음수";
  alert(`${num}${str} 입니다`);

}

// #btn1 버튼이 클릭 되었을 때
btn1.addEventListener("click", function(){
  // #input1에 작성된 값 얻어오기
  const value = Number(input1.value);
  // 함수 호출
  testFn1(value);

})

// ㅡㅡㅡㅡㅡㅡ★☆★☆★☆★☆ 함수 1개끝 ★☆★☆★☆★☆ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

/* 입력 받은 수 3개 합계 구하기 */
const btn2 = document.querySelector("#btn2");

function testFn2(num1, num2, num3){
  const sum = num1 + num2 + num3;
  alert(`합계 : ${sum}`);
}

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

  // 버튼 클릭 시점에 클래스가 "input2"인 요소 모두 얻어오기
  const inputs = document.querySelectorAll(".input2");
                 // NodeList(유사 배열 형태)queryAll 이기 때문!!

  const value1 = Number(inputs[0].value);
  const value2 = Number(inputs[1].value);
  const value3 = Number(inputs[2].value);

  testFn2(value1, value2, value3); // 함수 호출

});


/** 합계 구하기 (배열 버전)
 *  @param arr : 전달 받은 숫자 배열
 */
function testFn3( arr ){

  let sum = 0;

  for(let i = 0 ; i < arr.length ; i++) {
    sum += arr[i];    
  }

  alert(`합계 : ${sum}`);

}

// #btn3 클릭 시 testFn3 호출
document.querySelector("#btn3").addEventListener("click", function(){

  // 클래스가 input2인 요소를 모두 얻어와 저장(배열)
  const inputs = document.querySelectorAll(".input2");
 
  // inputs 요소 별로 값을 얻어와 숫자로 변환해 숫자 배열에 저장
 
  // 1) inputs 길이 만큼의 배열 생성
  const numberArr = new Array(inputs.length);

  // 2) inputs 각 인덱스 요소의 값을 얻어오기
  for(let i = 0; i < inputs.length; i++){
    const num = Number(inputs[i].value);
   
  // 3) numberArr의 i번째 인덱스 요소에 num 저장
    numberArr[i] = num; // 입력된 값이 모두 numberArr에 저장
  }

  // 합계 구하는 함수 호출
  testFn3( numberArr);

});

/* return 확인하기 1 */
/** num의 x 제곱을 반환하는 함수 */
function pow(num, x) {

  let result = 1; // 곱할 때 영향을 주지 않는 1로 초기화

  for(let i=0; i < x; i++){
    result *= num;
  }
  // 현재 함수를 종료,
  // result 값을 가지고 호출한 곳으로 돌아감
  return result;
}


/** 출력할 문자열을 반환하는 함수 */
function printStr(num){
  return `결과 : ${num}`;
}

// #btn4 클릭 시
document.querySelector("#btn4").addEventListener("click", function(){

  const num = Number(prompt("숫자 입력"));
  const x   = Number(prompt("몇 제곱?"));

  alert(printStr( pow(num, x) ));

})

/* return 확인하기 2 */
function testFn5aaa(num){
  return testFn5bbb(num) * 2;
}

function testFn5bbb(num){
  return testFn5ccc(num) * 3;
}

function testFn5ccc(num){
  return num + 1;
}

const btn5 = document.querySelector("#btn5");
btn5.addEventListener("click", function(){

  alert( testFn5aaa(3) );
  console.log(testFn5aaa(3));
})

/* 익명 함수 확인 */
const btn6 = document.querySelector("#btn6");

// 익명 함수를 이벤트 핸들러로 많이 사용하는 이유
// -> 해당 이벤트 전용 기능인 경우가 많아서
//   (다른 곳에서는 재사용을 못하는 경우가 많아서)
btn6.addEventListener("click", function(){ // 익명함수
  console.log("익명 함수 실행");

  /* 변수 + 익명 함수 */
  // 변수는 함수도 저장할 수 있다!!!! (자료형 : function)

  // 변수명이 익명 함수의 함수명 역할을 해준다!!
  // (요즘 함수 정의 방법 (function 단어 안쓰는게 트렌드다!!!) )
 
  // 해당 함수는 지역 변수에 저장됨
  // -> 해당 지역에서만 사용 가능한 함수
  const plusFn = function(a, b){
  return a+ b;
  }

  console.log( plusFn (1,2) );

});
 
  // 이름 있는 함수 선언/정의 -> 여러 곳에 재사용 가능
function testFn6(){
  console.log("이름 있는 함수 실행");
}

// 함수명만 작성 -> 함수코드가 그대로 반환
btn6.addEventListener("click", testFn6)

/* 매개 변수/return 익명 함수 전달하기 */
const btn7 = document.querySelector("#btn7");

function testFn7( otherFn ){
  // otherFn : 전달 받은 함수 코드

  return function(num){
    // otherFn() : 전달 받은 함수 호출(실행)
    return otherFn() + num;
   }

}

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

  testFn7( function(){ return 10; } )

  const resultFn = testFn7( function(){ return 10; })

// testFn7() 호출 결과로 받환 받은 함수
  // function(num){
  // return oherFn() + num;
  //}

  alert (resultFn(100) ); //

})

/* 화살표 함수 */
const arrows = document.querySelectorAll(".arrow"); // 버튼 4개

// 화살표 함수 기본 형태
arrows[0].addEventListener("click", () => {

  // 익명 함수를 변수에 대입
  const sumFn = (a, b, c) => {
    return a + b + c;
  }

  alert( sumFn(10,20,30 ));

});

// 매개 변수가 1개인 경우
arrows[1].addEventListener("click", () => {

  // 매개 변수 1개 --> () 생략 가능
  const testFn = num => {
    return 10 * num;
  }

  alert( testFn(99) );

});

/* 한 줄만 작성된 경우 */
arrows[2].addEventListener("click", () => {

  // 함수 정의 부분이 return 한 줄 --> { return } 생략 가능
  const minusFn = (a, b) => a - b;

  alert( minusFn(10, 3) ); // 7

  // 매개 변수 1개, 정의 내용 rreturn 한 줄
  const doubleFn = num => num * 2;

  console.log( doubleFn(3) ); // 6

});

//object를 return하는 경우
arrows[3].addEventListener("click", () => {
   
  // JS 객체 : { k:v, k:v, .... }
  // k(key)   == 변수명
  // v(value) == 대입되는 값

  // 정상 작성
  const objectFn = (name, age) => {
    return { "이름": name, "나이": age };
  }

  // 잘못 작성
  // const objectFn = (name, age) => { "이름": name, "나이": age };
 
  console.log(objectFn("홍윤기", 35));

});

/* 즉시 실행 함수 */

  (() => {
    console.log("[즉시 실행 함수 실행됨]");
    console.log("[점심 맛있게 드세요]");
  }) ()

/*    
    ccc부터 입력되서 하나씩 나감@@@@@@@@@@@
 ㅣ   ccc()    ㅣ
 ㅣ   bbb()    ㅣ
 ㅣ   aaa()    ㅣ
 ㅣ  alert()   ㅣ
 ㅣ이벤트핸들러ㅣ
컵ㅡㅡㅡㅡㅡㅡㅡ
*/

/* STACK 구조
 - 자료 구조 중 하나

 - 한 쪽으로만 들어가고
   한 쪽으로만 나오는 형태

 - 메모리에서 실행된 함수들을
   리스트업할 때 사용됨
   (함수 호출 구조는 Stack 형식)
   
 - 선입후출
   (First In Last Out, FILO)
   또는
   후입선출
   (Last In First Out, LIFO)
   
*/








//-------------------------------------------------

const lunch1 = document.querySelector(".lunch");
const ip = document.querySelector(".ip");

function lunch(num){


  if(num === 0) {
    alert("형제네");
  } else if(num === 1) {
    alert("서울초밥");
  }else {
    alert("남원추어탕");
  }

}




lunch1.addEventListener("click", function(){
 
  const value = Number(ip.value);
 
  lunch(value);

})

 

 

16_DOM탐색

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>16_DOM탐색</title>
</head>
<body>
 
  <h1>DOM(Document Object Model)</h1>

  <pre>
    HTML(웹문서, 웹페이지) 문서를 객체 기반으로 표현한 것
    -> HTML 문서에 작성된 내용을 트리구조(계층형으로 표현)로 나타냈을 때
        각각의 태그, TEXT, COMMENT 등을 Node라고 한다.

    document : {
        DOCTYPE : html,
        HTML : {
            HEAD : {
                TITLE : { TEXT : "문서 제목" },
                STYLE : {...},
                META : {...}
            } ,
            BODY : {
                H1 : { TEXT : "제목", ATTRIBUTE : "속성" },
                COMMNET : {TEXT : "주석 내용"},
                DIV : {...}
            }
        }
    }
  </pre>

  <hr>
  <h1>Node 탐색</h1>
  <pre>
    1) 부모 노드 탐색 : parentNode

    2) 첫 번째 자식 노드 탐색 : firstChild

    3) 마지막 자식 노드 탐색 : lastChild

    4) 원하는 위치(인덱스)에 존재하는 자식 노드 탐색
        : childNodes[인덱스]
   
    <!-- Sibling : 형제, 자매, 남매 -->
    5) 이전 형제 노드 탐색 : previousSibling
    6) 다음 형제 노드 탐색 : nextSibling
  </pre>

  <button id="checkBtn1">Node 탐색 확인하기</button>

  <ul id="test1">
    <!-- Node 확인 테스트 주석입니다. -->

    <li id="li1">1번</li>
    <li class="cls">2번</li>
    <!-- 중간 주석 -->
    <li style="background-color: yellow;">3번</li>
    <li>
        <a href="#">4번</a>
    </li></ul>

    <hr>

    <h1>Element(요소) 탐색 방법</h1>
    <pre>
      Node : 태그(요소 노드), 속성, 주석, 내용(텍스트 노드) 등을 모두 표현.

      Element : Node의 하위 개념으로 요소 노드만을 표현
 
 
      [Element만 탐색하는 방법]
 
      children : 자식 요소만 모두 선택
      parentElement : 부모 요소 선택
 
      firstElementChild : 첫 번째 자식 요소 선택
      lastElementChild  : 마지막 자식 요소 선택
 
      previousElementSibling : 이전 형제 요소 선택
      nextElementSibling     : 다음 형제 요소 선택
    </pre>

    <button id="checkBtn2">Element 탐색 확인</button>

    <ul id="test2">
      <!-- 테스트 주석입니다. -->

      <li>1번</li>
      <li class="cls">2번</li>
      <!-- 중간 주석 -->
      <li style="background-color: yellow;">3번</li>
      <li>
          <a href="#">4번</a>
      </li>
  </ul>

 



  <script src="../Js/16_DOM탐색.js"></script>
</body>
</html>

Javascript

const checkBtn1 = document.querySelector("#checkBtn1");

checkBtn1.addEventListener("click", () => {

  const test1 = document.querySelector("#test1"); // ul

  // 요소.childNodes -> 배열 형태(NodeList)로 반환

  // #test1의 모든 자식 노드 얻어오기
  const list = test1.childNodes;
  console.log(list);

  // 첫 번째 li 노드 선택
  console.log(list[3]);

  // 2) 요소.parentNode

  // #li1의 부모 노드 탐색 (JS는 부모 찾기 가능!!)

  const li1 = document.querySelector("#li1");
  console.log(li1.parentNode);

  // 3) 요소.firstChild : 첫 번째 자식 노드 탐색
  //    요소.lastChild  : 마지막  자식 노드 탐색

  // #test1의 첫째, 마지막 자식 노드 탐색
  console.log(test1.firstChild);
  console.log(test1.lastChild);

  // 마지막 li 요소의 배경색을 pink로 변경
  test1.lastChild.style.backgroundColor = "pink";

  // 4) 이전 형제 노드 탐색 : 요소.previousSibling
  //    다음 형제 노드 탐색 : 요소.nextSibling

  // list[9]의 다음, 다음 형제 노드 선택
  console.log(list[9].nextSibling.nextSibling);

  // list[5]의 이전, 이전 형제 노드 선택
  console.log(list[5].previousSibling.previousSibling);

})

/* Element 요소 탐석 */
const checkBtn2 = document.querySelector("#checkBtn2")

checkBtn2.addEventListener("click", () => {

  /*
  children : 자식 요소만 모두 선택
  parentElement : 부모 요소 선택
  firstElementChild : 첫 번째 자식 요소 선택
  lastElementChild  : 마지막 자식 요소 선택
  previousElementSibling : 이전 형제 요소 선택
  nextElementSibling     : 다음 형제 요소 선택
 */

  const test2 = document.querySelector("#test2"); //ul

  // #test2의 모든 자식 요소
  console.log(test2.children); // 자식요소 4개

  // #test2의 부모 요소
  console.log(test2.parentElement); // body 태그

  // #test2의 첫 번째 자식 요소
  console.log(test2.firstElementChild);

  // #test2의 마지막 자식 요소
  console.log(test2.lastElementChild);

  // #test2의 이전 형제 요소
  console.log(test2.previousElementSibling);

  // #test2의 다음 형제 요소
  console.log(test2.nextElementSibling);
})

 

 

17_DOM 요소 생성 / 추가 /제거

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>17_DOM요소생성,추가,제거</title>

  <link rel="stylesheet" href="../css/17_DOM요소생성,추가,제거.css">
</head>
<body>
  <h1>DOM 요소 생성 / 추가 / 제거</h1>

  <pre>
    [생성]
    1) document.createTextNode ("내용") -> TEXT 노드 생성
    2) document.createElement("태그명") -> HTML 요소 생성

    * 노드/요소가 생성만 된 것이지
      아직 화면(document)에 추가된 것은 아님!!!
   
    [추가]
    1) 요소.appendChild(노드/요소)
       -> 요소 내부에 마지막 자식 노드/요소로 추가

    2) 요소.append(요소[, 요소2, 요소3 ...])
       -> 지정된 요소 내부에
          () 내 요소를 마지막 자식으로 순서대로 추가
   
    3) 요소.prepend(요소[, 요소2, 요소3 ...])
       -> 지정된 요소 내부에
          () 내 요소를 첫 번째 자식으로 순서대로 추가

    4) 요소.before(요소)
       -> 지정된 요소의 이전 형제(앞에) 추가

    5) 요소.after (요소)
       -> 지정된 요소의 다음 형제(뒤에) 추가

    [제거]
    요소.remove()
      -> 지정된 요소를 제거
    </pre>

    <div class="container">
      <div id="standard" class="box" style="background-color: yellow;"></div>
    </div>

    <button class="btn">prepend</button>

    <button class="btn">append</button>

    <button class="btn">before</button>

    <button class="btn">after</button>

    <button class="btn">remove</button>


 



  <script src="../Js/17_DOM요소생성,추가,제거.js"></script>
</body>
</html>

 

 

CSS

div{
  border: 1px solid black;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container{
  width: 502px;
  height: 302px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.box{
  width: 100px;
  height: 100px;

  /* 내용 자동 줄바꿈 */
  word-break: break-all;
}

 

Javascript


// 기준이 되는 박스
const standard = document.querySelector("#standard");

const btns = document.querySelectorAll(".btn"); // 버튼들


let count = 1; // 1씩 증가하면서 요소 내용으로 추가

// 모든 버튼에 클릭 이벤트 추가
for(let i=0 ; i<btns.length ; i++){

  btns[i].addEventListener("click", () => {

    const str = btns[i].innerText; // 작성된 버튼 내용
    console.log(str);

    switch(str){
      case "prepend" :
        const span1 = document.createElement("span"); // span 생성
        span1.innerText = count; // span 내용으로 count 추가
        span1.style.backgroundColor = "skyblue";
        standard.prepend(span1); // #standard 첫 번째 자식으로 span1 추가
      break;

      case "append" :
        const span2 = document.createElement("span");
        span2.innerText = count;
        span2.style.backgroundColor = "lightsalmon";
        standard.append(span2); // #standard 마지막 자식으로 span2 추가
        break;

      case "before":
        const div1 = document.createElement("div"); // div 요소 생성
        div1.innerText = count; // 내용으로 count 추가
        div1.style.backgroundColor = "greenyellow"; // 배경색 추가
        div1.className = "box"; // box 클래스 추가
        standard.before(div1); // #standard 앞쪽에 추가  
      break;

      case "after" :
        const div2 = document.createElement("div");
        div2.innerHTML = count;
        div2.style.backgroundColor = "orange";
        div2.className = "box";
        standard.after(div2);  // #standard 뒷쪽에 추가
      break;

      case "remove" :
        // .container 요소를 제거
        document.querySelector(".container").remove();
      break;

    }

    count++; //count 1 증가

  });

}

18_색변경v2

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>18_색변경vs</title>

  <link rel="stylesheet" href="../css/18_색변경v2.css">
</head>
<body>
 
  <h3>요소 탐색을 이용한 JS 코드 업그레이드</h3>

  <main>
    <section class="color-area">

      <div class="container">
        <div class="box"></div>
        <input type="text" class="color-input">
      </div>
      <div class="container">
        <div class="box"></div>
        <input type="text" class="color-input">
      </div>
      <div class="container">
        <div class="box"></div>
        <input type="text" class="color-input">
      </div>
      <div class="container">
        <div class="box"></div>
        <input type="text" class="color-input">
      </div>
      <div class="container">
        <div class="box"></div>
        <input type="text" class="color-input">
      </div>
    </section>

    <button id="changeButton">색상 변경</button>
  </main>




  <script src="../Js/18_색변경v2.js"></script>
</body>
</html>

CSS

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

main{
  width: 600px;
  margin: 50px auto;
  text-align: center;
}

.color-area{
  display: flex;
  justify-content: space-between;
}

.container{
  width: 18%;
  display: flex;
  flex-direction: column;
}

.box{
  width: 100%;
  height: 108px;
  border: 1px solid black;
  transition-duration: 0.5s;
}

.color-input{
  width: 100%;
  height: 20px;
}

#changeButton{
  width: 80%;
  margin-top: 10px;
  background-color: white;
  border : 2px solid pink;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
}

#changeButton:hover{
  color : white;
  background-color: pink;
}

#changeButton:active{
  border: 2px solid black;
}

Javascript

// 색 입력 input 태그들
const inputList = document.querySelectorAll(".color-input");

// 변경 버튼
const changeButton = document.querySelector("#changeButton");

changeButton.addEventListener("click", () => {

  for(let i=0 ; i<inputList.length; i++){
    // 색상이 입력된 input의 이전 요소 === .box 요소
    const box = inputList[i].previousElementSibling;
    box.style.backgroundColor = inputList[i].value;
  }

})

/* 같은 인덱스를 이용하는 방법은 한계가 존재하기 때문에
  대상 요소를 확실하게 선택한 후 탐색 코드를 이용해서
  찾아가 원하는 코드/기능을 적용 하는 것이 좋다!!!
*/

 

19_합계구하기

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>19_합계구하기</title>

  <link rel="stylesheet" href="../css/19_합계구하기.css">
</head>
<body>
 
  <main>
    <button id="add"> 추가</button>
    <button id="calc">계산</button>

    <div class="container">
      <!-- 2줄 까지가 기본 -->
      <div class="row">
        <input type="text" class="input-number">
      </div>
      <div class="row">
        <input type="text" class="input-number">
      </div>

      <!-- 추가 버튼 클릭 시 생성되는 요소 샘플
      &times; : x 모양 특수기호 -->
      <div class="row">
        <input type="text" class="input-number">

       
        <span class="remove-row">&times;</span>
      </div>

    </div>

  </main>



  <script src="../Js/19_합계구하기.js"></script>
</body>
</html>

 

CSS

.row{
  margin: 5px 0;
}

/* x버튼 */
.remove-row{
  display: inline-block;
  margin-left: 5px;
  font-size: 20px;
  cursor: pointer;
  user-select: none;
}

.remove-row:hover{
  font-weight: bold;
}

.remove-row:active{
  font-weight: bold;
  color:red;
}.row{
  margin: 5px 0;
}

/* x버튼 */
.remove-row{
  display: inline-block;
  margin-left: 5px;
  font-size: 20px;
  cursor: pointer;
  user-select: none;
}

.remove-row:hover{
  font-weight: bold;
}

.remove-row:active{
  font-weight: bold;
  color:red;
}

 

Javascript

/* 계산하기 */
const calc = document.querySelector("#calc");

calc.addEventListener("click", () => {

  // 계산 버튼 클릭 시점에 존재하는 .input-number 모두 얻어오기
  const numbers = document.querySelectorAll(".input-number")

  let sum = 0;

  for( i= 0; i < numbers.length ; i++){
    sum += Number(numbers[i].value);
  }

  alert(`합계 : ${sum}`)

})

/* 추가 버튼 */
const addBtn = document.querySelector("#add"); // 버튼

// 감싸는 요소
const container = document.querySelector(".container");

addBtn.addEventListener("click", () => {

  // 추가 버튼 클릭 시
  // div, input, span 요소를 생성해서 알맞게 조립 후
  // .container의 마지막 자식으로 추가

  // 1) div 만들기
  const div = document.createElement("div");
  div.className = "row" // row 클래스 추가

  // 2) input 만들기
  const input = document.createElement("input");
  input.type = "text";
  input.className = "input-number";


  // 3) span 만들기
  const span = document.createElement("span");
  span.className = "remove-row"
  span.innerHTML = "&times;"; // HTML 특수 문자는 innerHTML 이용

  // ******************************************************
  // x버튼(span)이 만들어질 때
  // 클릭 되었을 때 동작을 같이 정의해줌!!!

  span.addEventListener("click", () => {
   
    // 클릭된 x 버튼의 부모(div.row)를 제거
    span.parentElement.remove();      

  });


  // ******************************************************


  // 4) 알맞게 조립
  // - 요소.append(A,B,C) : 마지막 자식으로 추가
  div.append(input, span);

  // 5) 조립된 div를 .container의 마지막 자식으로 추가
  container.append(div);

 
}
 
)

// 페이지 로딩 시점에 존재하는 .remove-row를 모두 얻어오기
// -> 처음에 x 버튼이 없어서 아래 for문 실행 X

// const xBtns = document.querySelectorAll(".remove-row");

// for(let i=0 ; i < xBtns.length ; i++){
//   xBtns[i].addEventListener("click", ()=>{
//     console.log("x클릭됨")
//   })
// }

 

반응형