장바구니 기능을 만들어 보는 시간!
유저가 구매버튼을 누르면 그 상품명을 어딘가 저장하면 끝인데
실제 서비스였으면 서버로 보내서 DB에 저장하는게 좋지만
우리는 서버가 없기 때문에 브라우저 저장공간을 이용하면 된다
크롬 개발자도구의 Application 탭 들어가보면
Local Storage / Session Storage (key:value 형태로 문자, 숫자 데이터 저장 가능)
Indexed DB (크고 많은 구조화된 데이터를 DB처럼 저장가능)
Cookies (유저 로그인정보 저장공간)
Cache Storage (html css js img 파일 저장해두는 공간)
Local Storage / Session Storage는 문자, 숫자는 key:value 형태로 저장가능하고 5MB까지만 저장 가능하다
Local Storage는 브라우저 재접속해도 영구적으로 남아있지만
Session Storage는 브라우저를 끄면 날아간다 (휘발성)
localStorage.setItem('이름', 'kim') //자료저장하는법
localStorage.getItem('이름') //자료꺼내는법
localStorage.removeItem('이름') //자료삭제하는법
수정하는 법은 따로 없고 꺼내서 수정하고 다시 저장하면 된다
array/object를 Local Storage에 저장하면 강제로 문자로 바꿔서 저장이된다
약간 편법을 사용하자면 array/object를 JSON으로 바꾸면 문자취급을 받기 때문에 안전하게 저장할 수 있다
var arr = [1,2,3];
var newArr = JSON.stringify(arr);
localStorage.setItem('num', newArr)
var arr = [1,2,3];
var newArr = JSON.stringify(arr);
localStorage.setItem('num', newArr);
//꺼내서 쓸 땐
var 꺼낸거 = localStorage.getItem('num');
꺼낸거 = JSON.parse(꺼낸거);
console.log(꺼낸거);
JSON으로 저장했기 떄문에 꺼내도 JSON이라 꺼낸 걸 다시 array/object로 바꾸고 싶으면 JSON.parse() 안에 넣으면 된다.
array/object -> JSON 변환하고 싶으면 JSON.stringify()
JSON -> array/object 변환하고 싶으면 JSON.parse()
(팁1) 내가 누른 요소의 형제요소(sibling) 찾는 법을 알아봐야한다
(팁2) localStorage가 비어있을 때는 array를 추가하면 되지만 localStorage에 이미 뭐가 있을 때는 array를 수정해야한다
카드 레이아웃을 생성하는 코드에 <button class="buy">구매</button>
를 추가한다
를 코드로 짜면 된다!
<script>
$('.buy').click(function(e){
let title = $(e.target).siblings('h5').text();
});
</script>
👆 그리고 구매 버튼에 이벤트 리스너 붙이기
$(e.target) -> click하는 대상
.sibling() -> 내 형제요소를 찾아주는 jQuery
<script>
$('.buy').click(function(e){
let title = $(e.target).sibling('h5').text();
loscalStorage.setItem('cart', JSON.stringify[title])
});
</script>
👆 localStorage에 저장까지 완료!
문제는 구매버튼을 누를때마다 array가 새로 생성만 되고 추가는 안된다
그래서 "이미 저장되어있으면 새로 추가하지말고 수정해주세요" 라는 코드를 짜야한다
<script>
$('.buy').click(function(e){
let title = $(e.target).sibling('h5').text();
if (localStorage.getItem('cart') != null){
수정해주세요~
} else {
loscalStorage.setItem('cart', JSON.stringify[title])
}
});
</script>
👆 'cart' 항목이 없을 때 getItem() 을 사용하면 null이 출력된다
localStorage에 직접 수정하는 문법은 없기 때문에 꺼내서 수정하고 다시 집어넣으면 된다
<script>
$('.buy').click(function(e){
let title = $(e.target).sibling('h5').text();
if (localStorage.getItem('cart') != null){
let 꺼낸거 = JSON.parse(localStorage.cart); // 혹은 JSON.parse(localStorage.getItem("cart"));
꺼낸거.push(title);
localStorage.setItem('cart', JSON.stringify(꺼낸거));
} else {
loscalStorage.setItem('cart', JSON.stringify[title])
}
});
</script>
<div class="row">장바구니페이지</div>
장바구니 페이지 div 박스 만든 후
<script>
// localStorage에서 cart꺼내주세요
// array 갯수만큼 p 생성해주세요
localStorage.getItem("cart");
let cart = JSON.parse(localStorage.getItem("cart"));
cart.forEach(function (a, i) {
let 장바구니상품 = `<p>${a}</p>`;
$(".row").append(장바구니상품);
});
</script>