JAVASCRIPT - 초급 10편

MJ·2022년 7월 25일
0

JAVASCRIPT 정리

목록 보기
10/22
post-thumbnail

* 데이터바인딩

데이터바인딩 : 제공자와 소비자로부터 데이터 원본을 결합시켜 이것들을 동기화하는 기법

"데이터를 원하는 곳에 뿌려주는것"

ex )
html
<div class="card-group container">
        <div class="card">
          <img src="https://via.placeholder.com/600">
          <div class="card-body">
            <h5>Card title</h5>
            <p>가격 : 70000</p>
            <button class="btn btn-danger">주문하기</button>
          </div>
        </div>
        <div class="card">
          <img src="https://via.placeholder.com/600">
          <div class="card-body">
            <h5>Card title</h5>
            <p>가격 : 70000</p>
            <button class="btn btn-danger">주문하기</button>
          </div>
        </div>
        <div class="card">
          <img src="https://via.placeholder.com/600">
          <div class="card-body">
            <h5>Card title</h5>
            <p>가격 : 70000</p>
            <button class="btn btn-danger">주문하기</button>
          </div>
        </div>
      </div>
javascript
var products = [
          { id : 0, price : 70000, title : 'Blossom Dress' },
          { id : 1, price : 50000, title : 'Springfield Shirt' },
          { id : 2, price : 60000, title : 'Black Monastery' }
        ]; // 원하는 데이터를 html에 필요한 곳에 각각 저장
//반복문 없이 일일이
        document.querySelectorAll('.card-body h5')[0].innerHTML = products[0].title;
        document.querySelectorAll('.card-body p')[0].innerHTML = '가격 : ' + products[0].price
        document.querySelectorAll('.card-body h5')[1].innerHTML = products[1].title;
        document.querySelectorAll('.card-body p')[1].innerHTML = '가격 : ' + products[1].price;
        document.querySelectorAll('.card-body h5')[2].innerHTML = products[2].title;
        document.querySelectorAll('.card-body p')[2].innerHTML = '가격 : ' + products[2].price;
//반복문 사용 : 반복문을 사용하면 data가 추가되거나 수정됬을때 용이
for(const i=0; i<products.length; i++) {
            document.querySelectorAll('.card-body h5')[i].innerHTML = products[i].title;
            document.querySelectorAll('.card-body p')[i].innerHTML = '가격 : ' + products[i].price
        }

* 문자 중간에 변수 삽입

1. +(결합 연산자)(대상이 모두 숫자일때는 덧셈, 이외 모두 문자열 결합

ex)
var a = 'New';
console.log("Hello" + a + "World"); // result : HelloNewWorld
//문자열 사이에 공백을 사용해야 공백이 적용된다
console.log("Hello " + a + " World") // reuslt : Hello New World

2. ${변수} (백틱 기호) 사용

var a = 'New';
console.log(`Hello ${a} World`); // result : Hello New World

* js로 html 수정

Element.insertAdjacentHTML(위치, 특정 텍스트) : HTML or XML 같은 특정 텍스트를 파싱하고, 특정 위치에 DOM tree 안에 원하는 node들을 추가

beforebegin : 요소 앞에
afterend : 요소 뒤에
beforeend : 요소 안에 가장 마지막 자식
afterbegin : 요소 안에 가장 첫번째 자식
ex)
js
var tem = '<p class="hi">Hello</p>';
        document.querySelector("#test").insertAdjacentHTML('beforeend', tem);
        // #test요소의 가장 맨뒤에 자식에 tem이라는 변수(특정 텍스트) 추가
특정 예시
모자 선택시 옵션 제거, 셔츠 선택시 옵션 출력, 바지 선택시 옵션 값 변경하여 출력
html
<style> .form-hide { display : none } </style>
<form class="container my-5 form-group">
        <p>상품선택</p>
        <select class="form-select mt-2">
            <option>모자</option>
            <option>셔츠</option>
            <option>바지</option>
        </select>
        <select class="form-select mt-2 form-hide">
            <option>95</option>
            <option>100</option>
        </select>
    </form>
javascript
document.getElementsByTagName("select")[0].addEventListener("input", function() { // input 값이 변화할때
            if(document.getElementsByTagName("select")[0].value == "셔츠" ) { // input 값이 셔츠일때
                document.getElementsByTagName("select")[1].classList.remove("form-hide"); // 옵션 출력
            } else if (document.getElementsByTagName("select")[0].value == "바지" ) { // input 값이 바지일때
                document.getElementsByTagName("select")[1].classList.remove("form-hide"); // 옵션 변경 후 출력
                var tem = `<option>28</option>
                <option>30</option>`; // 바지 사이즈 옵션
                document.getElementsByTagName("select")[1].innerHTML = tem;
            } else if (document.getElementsByTagName("select")[0].value == "모자") { // input 값이 모자일때
                document.getElementsByTagName("select")[1].classList.add("form-hide"); // 옵션 제거
            }
        });
profile
A fancy web like a rose

0개의 댓글