TIL 211214

devyoon99·2021년 12월 14일
0

TIL

목록 보기
38/38
post-thumbnail

자바스크립트 / 변수를 빈 값으로 만들기

변수 = "";

let a = 123123;
a = "";
console.log(a); // "" 빈 값이 뜬다.
  • 변수선언시 값을 설정하지 않는 경우
let a;
console.log(a) //undefined가 뜬다.

자바스크립트 / 변수에 값을 추가하기

변수 = 변수 + 3

  • 변수의 이전에 저장된 값에 새로운 값을 추가하는 것이다.
let a = 0;

a = a + 2;

a = a + 4;

//a는 6이다.

a = 1 + 2;

  • 변수 a의 이전에 저장되어있던 값을 지우고, 3을 저장시킨다.

UI / 한 글자씩 입력되는 애니매이션 만들기

html

<h1>abcde</h1>
<button>버튼</button>

요약

  • 문자열의 글자를 일부분 떼오고, 변수에 추가시킨후에, h1 tag의 content에 넣음
    • "a" -> "ab" -> "abc" -> ... -> "abcde"
let text = $("h1").text();
//h1 tag의 content를 변수에 저장한다.

$("button").on("click", function () {
  $("h1").text("");
  //h1 tag의 content를 없앤다.
  
  typetext = "";
  //빈 변수를 만든다.
  
  setTimeout(() => {
    typetext = typetext + text[0];
    //문자열의 맨 처음 알파벳을 빈 변수에 저장시킨다.
    
    $("h1").text(typetext);
    //h1 tag에 content에 "a"를 넣는다.
  }, 500);
  //0.5초 실행시킨다.
  setTimeout(() => {
    typetext = typetext + text[1];
    //"a"가 담긴 변수에 "b"를 추가한다. -> "ab"
    
    $("h1").text(typetext);
    //h1 tag에 content에 "ab"를 넣는다.
    
  }, 1000);
    //1초후에 실행시킨다.
  
  setTimeout(() => {
    typetext = typetext + text[2];
    $("h1").text(typetext);
  }, 1500);
  setTimeout(() => {
    typetext = typetext + text[3];
    $("h1").text(typetext);
  }, 2000);
  setTimeout(() => {
    typetext = typetext + text[4];
    $("h1").text(typetext);
  }, 2500);
});

확장성있게 코드를 수정

  • 코드가 0,1,2,3,4 숫자만 다르고 나머지는 같음 -> 반복문화
    • 단, 500, 1000, 1500, 2000... 반복문화 가능
    • 5001, 5002, 500*3 곱하기로 분리가능하기 때문이다
  • h1 tag의 content에 글자가 추가하더라도, 실행되도록 반복문 변수 i의 범위를 문자열의 길이로 조정
$("button").on("click", function () {
  $("h1").text("");
  //h1 tag의 content를 없앤다.
  
  typetext = "";
  //빈 변수를 만든다.
  
  for (let i = 0; i < text.length; i++) {
    setTimeout(() => {
      typetext = typetext + text[i];
      $("h1").text(typetext);
    }, 500 * i);
  }
});

물건 판매 사이트 만들기


트러블 슈팅

1) 동적 html 만들기에서 문제발생

결론1 : 동적 html을 만들 때, 반복문 변수 i를 html의 class에 넣음(class="product-name${i}"), 그래서 내가 원하는 위치의 카드에 원하는 데이터를 넣을 수 있게 되었음

  • 만들고 싶은 것 : 식기세척기의 를 검색하면, 식기세척기의 상품카드가 떠야한다.
  • 목표 : 를 검색하면, 원목침대프임과 시원한 서큘이터 2가지 상품 카드가 떠야한다.
  • 과정
    • MakeProductCard(2)를 통해서 2가지 상품카드 html을 만듬
    • inputProductData(1)을 통해서 상품카드에 데이터를 넣으려고 했음
  • 문제상황
    • 나는 첫번째 카드에는 원목침대프레임 데이터를 넣고, 2번째 카드에는 시원한 서큘레이터의 데이터를 넣고 싶었음
    • 둘다 원목침대거나 둘다 서큘레이터거나 이런 식으로 만들어짐

문제 코드

//상품 카드 만드는 함수
function MakeProductCard(NumberOfCard) {
  let productCard = "";
  let productPrice = "";
  for (let i = 0; i < NumberOfCard; i++) {
    productCard += `<div class="product-card">
    <div class="img-box">
      <img src="pr1.JPG" class="img"/>
    </div>
    <div class="product-text">
      <p class="product-name product-name"></p>
      <p class="product-seller product-seller"></p>
    </div>
  </div>`;

    productPrice += `<div class="product-price">
    <span class="product-price__number product-price__number"></span>
      </div>`;
  }

  $(".product-card__container").append(productCard);
  $(".product-price__container").append(productPrice);
}

//상품데이터
```json
{
  "products": [
    {
      "id": 0,
      "product_name": "식기세척기",
      "brand_name": "세척나라",
      "photo": "pr1.jpg",
      "price": 100000
    },
    {
      "id": 1,
      "product_name": "원목 침대 프레임",
      "brand_name": "침대나라",
      "photo": "pr2.jpg",
      "price": 200000
    },
    {
      "id": 2,
      "product_name": "천연 디퓨저 세트",
      "brand_name": "향기나라",
      "photo": "pr3.jpg",
      "price": 300000
    },
    {
      "id": 3,
      "product_name": "시원한 서큘레이터",
      "brand_name": "바람나라",
      "photo": "pr4.jpg",
      "price": 400000
    },
    {
      "id": 4,
      "product_name": "맥북",
      "brand_name": "애플나라",
      "photo": "pr4.jpg",
      "price": 1500000
    }
  ]
}
//상품카드에 데이터 넣는 함수
function inputProductData(data) {
  $.ajax({
    url: "store.json",
    type: "GET",
  }).done(function (e) {
    $(".img").attr("src", e.products[data].photo);
    $(".product-name").text(e.products[data].product_name);
    $(".product-seller").text(e.products[data].brand_name);
    $(".product-price__number").text(e.products[data].price);
  });
}

//검색 매커니즘
$(".input").on("input", function () {
  $(".product-card__container").html("");
  $(".product-price__container").html("");
  if ($(".input").val() === "레" || $(".input").val() === "원") 
  //input창에 `레` 검색하는 것을 인지한다.
    $(".product-card__container").html("");
    $(".product-price__container").html("");
    MakeProductCard(2);
    inputProductData(1);
    inputProductData(3);
  } else if (){}
  ...
} 
  • 카드를 만들고, 데이터넣음
    • 카드 2개 만들었음
    • 카드 한 개는 원목데이터, 나머지는 서큘레이터 넣을려고 했는데, 데이터를 넣으면, 둘다 원목으로 바뀌거나 둘다 서큘레이터로 바뀜
MakeProductCard(2);
inputProductData(0);

해결코드

  • 상품카드를이 구분되도록 만들었음
    • 상품카드를 만들 때, 반복문 변수 i를 상품 카드 html의 클래스에 추가하였음
    • 처음 카드의 상품 카드의 제목 tag를 가져오고 싶다.
      • 내가 원하는 위치의 카드를 가져올 수 있게 되었다.
      • $(".product-name0")
      • $(".product-name1")
      • ...
  • 결론 : 내가 원하는 위치의 카드에 데이터를 넣을 수 있게 되었음
function MakeProductCard(NumberOfCard) {
  let productCard = "";
  let productPrice = "";
  for (let i = 0; i < NumberOfCard; i++) {
    productCard += `<div class="product-card">
    <div class="img-box">
      <img src="pr1.JPG" class="img${i}"/>
    </div>
    <div class="product-text">
      <p class="product-name product-name${i}"></p>
      <p class="product-seller product-seller${i}"></p>
    </div>
  </div>`;

    productPrice += `<div class="product-price">
    <span class="product-price__number product-price__number${i}"></span>
      </div>`;
  }

  $(".product-card__container").append(productCard);
  $(".product-price__container").append(productPrice);
}

function inputProductData(NumberOfCard, data) {
  $.ajax({
    url: "store.json",
    type: "GET",
  }).done(function (e) {
    $(".img" + NumberOfCard).attr("src", e.products[data].photo);
    $(".product-name" + NumberOfCard).text(e.products[data].product_name);
    $(".product-seller" + NumberOfCard).text(e.products[data].brand_name);
    $(".product-price__number" + NumberOfCard).text(e.products[data].price);
  });
}

문제상황 : 2) 기를 검색하면, 식기세척기 카드가 뜨는 데, 이때 식기세척기의 기 글자만 노란색으로 배경색을 바꾸고 싶다,

  • 아직 못했음

json 데이터 저장방식

  • 데이터를 저장하는 방법중 하나이다.
  • 파일명
    • vsc에서는 이름뒤에 .json을 붙여라
  • 문법특징
    • 이름은 반드시 "" 쌍따옴표안에 작성해야한다.
//json 데이터 문법
{
  "products": [
    {
      "id": 0,
      "product_name": "식기세척기",
      "brand_name": "세척나라",
      "photo": "pr1.jpg",
      "price": 100000
    },
    {
      "id": 1,
      "product_name": "원목 침대 프레임",
      "brand_name": "침대나라",
      "photo": "pr2.jpg",
      "price": 200000
    },
    {
      "id": 2,
      "product_name": "천연 디퓨저 세트",
      "brand_name": "향기나라",
      "photo": "pr3.jpg",
      "price": 300000
    },
    {
      "id": 3,
      "product_name": "시원한 서큘레이터",
      "brand_name": "바람나라",
      "photo": "pr4.jpg",
      "price": 400000
    }
  ]
}
  • 데이터 사용하기
    • jQuery
    • url에 주소를 복붙하거나, 파일명.json 둘중 하나를 사용하면 된다.
$.ajax({
  url: "store.json"
  type: "GET"
}).done(function(e){
  $(".product-name").html(e.products[0].brand_name);
})

0개의 댓글

관련 채용 정보