2 글 보임 - 1 에서 2 까지 (총 2 중에서)
-
글쓴이글
-
2023년 3월 9일 18:55 #71641
서현참가자응용 2번까지 5시간 머리싸매고,, 해결을 했습니다. 다만 앞의 수업에서 만들었던 다나가순 정렬, 6만원 이하 상품만 보이기 등의 버튼을 누르고 나서 장바구니 담기 버튼을 클릭하면 localStorage에 저장이 되지 않는데 그 이유가 궁금하고 해결하고 싶습니다. 이유가 뭘까요????
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>장바구니 응용2</title> <!-- Bootstrap CDN --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="row"> <!-- <div class="col-sm-4"> < img src="https://via.placeholder.com/600" class="w-100"> <h5>Card title</h5> <p>가격 : 70000</p> </div> --> </div> </div> <div class="container"> <button class="btn btn-danger" id="six">6만원 이하의 상품만 보여주기</button> </div> <!-- Bootstrap Script --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"> </script> <!-- JQery CDN --> <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"> </script> <script> var products = [ { id: 0, price: 70000, title: 'Blossom Dress' }, { id: 1, price: 50000, title: 'Springfield Shirt' }, { id: 2, price: 60000, title: 'Black Monastery' } ]; function 상품(products) { products.forEach((a, i) => { var template = `<div class="col-sm-4"> < img src="https://via.placeholder.com/600" class="w-100"> <h5>${products[i].title}</h5> <p>가격 : ${products[i].price}</p> <button class='buy'>담기</button> </div>`; $(".row").append(template); } ) } 상품(products); //2. 6만원 이하 상품만 보여주는 버튼 기능 개발하기(feat. filter) $('#six').on('click', function () { var six = products.filter(function (a) { return a.price <= 60000 //조건식 }) $('.row').html('') console.log(six); 상품(six); })
//응용2) 같은 상품 담기를 누르면 상품의 갯수가 올라가도록 코드 작성해보기----------------------------------------------------- $('.buy').click(function (e) { var name = $(e.target).siblings('h5').text();//선택한 요소의 이름 var item = JSON.parse(localStorage.getItem('cart'));//array console.log('e.target name :' + name); // Blossom Dress 등 각각의 상품명이 출력됨 if (item == null) { localStorage.setItem('cart', JSON.stringify([{ name, count: 1 }])); } else if (item.find(title => title.name === name) !== undefined) { let answer = item.find(title => title.name === name); console.log('answer' + answer.name); answer.count++; localStorage.setItem('cart', JSON.stringify(item)); } else if (item.find(title => title.name === name) == undefined) { item.push({ name, count: 1 }); localStorage.setItem('cart', JSON.stringify(item)); } }) </script> </body> </html>
-
글쓴이글
2 글 보임 - 1 에서 2 까지 (총 2 중에서)
- 답변은 로그인 후 가능합니다.