결제 통합을 통해 HTMLCSS 및 JS에서 간단한 장바구니를 만드는 방법
If you want to create your own shopping cart in HTM5, CSS3, and JS, you are in the right place! This is how to create a shopping cart. This also includes Payment integration from the Payment Request API!
1. Create the files
Create a folder and put these files in it:
- index.html
- style.css
- script.js
2. Add HTML
Put this in index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shopping Cart</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="products"> <div class="product"> <h2>Product 1</h2> <p>$10</p> <button onclick="addToCart('Product 1', 10)">Add to Cart</button> </div> <!-- Add more products as needed --> </div> <div class="cart"> <h2>Shopping Cart</h2> <ul id="cart-items"></ul> <p>Total: $<span id="cart-total">0</span></p> </div> <script src="script.js"></script> </body> </html>
3. Add CSS
Put this in style.css:
.products, .cart { margin: 20px; } .product, .cart-item { margin-bottom: 10px; }
4. Add Javascript
Put this in script.js:
let cart = []; function addToCart(name, price) { const item = cart.find(product => product.name === name); if (item) { item.quantity++; } else { cart.push({ name, price, quantity: 1 }); } updateCart(); } function removeFromCart(name) { cart = cart.filter(product => product.name !== name); updateCart(); } function updateCart() { const cartItems = document.getElementById('cart-items'); const cartTotal = document.getElementById('cart-total'); cartItems.innerHTML = ''; let total = 0; cart.forEach(product => { const li = document.createElement('li'); li.textContent = `${product.name} - $${product.price} x ${product.quantity}`; const removeButton = document.createElement('button'); removeButton.textContent = 'Remove'; removeButton.onclick = () => removeFromCart(product.name); li.appendChild(removeButton); cartItems.appendChild(li); total += product.price * product.quantity; }); cartTotal.textContent = total; } const paymentRequest = new PaymentRequest( [ { supportedMethods: 'basic-card', data: { supportedNetworks: ['visa', 'mastercard'], }, }, ], { total: { label: 'Total', amount: { currency: 'USD', value: '10.00' }, }, } ); paymentRequest.show().then((paymentResponse) => { // Process the payment console.log(paymentResponse); // Complete the payment paymentResponse.complete('success').then(() => { console.log('Payment completed successfully'); }); }).catch((error) => { console.error('Payment failed', error); });
5. Explaining the JS file
1. Shopping cart functionality
- Initialize the cart
let cart = [];
- cart: An empty array to store items added to the cart.
2 Add items to the cart
function addToCart(name, price) { const item = cart.find(product => product.name === name); if (item) { item.quantity++; } else { cart.push({ name, price, quantity: 1 }); } updateCart(); }
- addToCart(name, price): Function to add items to the cart.
- cart.find(product => product.name === name): Searches for an item in the cart by name.
- if(item): If an item is found, it increments the quantity.
- else: If the item is not found, it adds a new item to the cart with the specified name, price, and a quantity of 1.
- updateCart(): Calls the updateCart function to refresh the cart display.
3 Remove items from the cart
function removeFromCart(name) { cart = cart.filter(product => product.name !== name); updateCart(); }
- removeFromCart(name): Function to remove items from the cart.
- cart.filter(product => product.name !== name): Filters out the item with the specified name from the cart.
- updateCart(): Calls the updateCart function to refresh the cart display.
4 Update the cart display
function updateCart() { const cartItems = document.getElementById('cart-items'); const cartTotal = document.getElementById('cart-total'); cartItems.innerHTML = ''; let total = 0; cart.forEach(product => { const li = document.createElement('li'); li.textContent = `${product.name} - $${product.price} x ${product.quantity}`; const removeButton = document.createElement('button'); removeButton.textContent = 'Remove'; removeButton.onclick = () => removeFromCart(product.name); li.appendChild(removeButton); cartItems.appendChild(li); total += product.price * product.quantity; }); cartTotal.textContent = total; }
- updateCart(): Function that updates the cart display.
- cartItems: Gets the HTML element with the ID cart-items.
- cartTotal: Gets the HTML element with the ID cart-total.
- cartItems.innerHTML = '': Clears the current cart items display.
- let total = 0: Initializes the total amount to 0.
- cart.forEach(product => { ... }): Iterates over each product in the cart.
- document.createElement('li'): Creates a new list item element.
- li.textContent = ${product.name} - $${product.price} x ${product.quantity}: Sets the text content of the list item.
- document.createElement(‘button’): Creates a new button element.
- removeButton.textContent = 'Remove': Sets the text content of the button.
- removeButton.onclick = () => removeFromCart(product.name): Sets the button’s click event to call removeFromCart.
- li.appendChild(removeButton): Adds the button to the list item.
- cartItems.appendChild(li): Adds the list item to the cart items display.
- total += product.price * product.quantity: Adds the product's total price to the total amount.
- cartTotal.textContent = total: Updates the total amount display.
Payment Request API
- Create a Payment Request object
const paymentRequest = new PaymentRequest( [ { supportedMethods: 'basic-card', data: { supportedNetworks: ['visa', 'mastercard'], }, }, ], { total: { label: 'Total', amount: { currency: 'USD', value: '10.00' }, }, } );
- PaymentRequest: Creates a new payment request.
- supportedMethods: Specifies the payment methods supported (e.g., ‘basic-card’).
- data: Contains additional information about the payment method, such as supported networks.
- total: Represents the total amount to be charged.
2 Show the Payment Request
paymentRequest.show().then((paymentResponse) => { // Process the payment console.log(paymentResponse); // Complete the payment paymentResponse.complete('success').then(() => { console.log('Payment completed successfully'); }); }).catch((error) => { console.error('Payment failed', error); });
- show(): Displays the payment interface to the user.
- then((paymentResponse) => { ... }): If the user approves the payment, this promise resolves with a paymentResponse object.
- paymentResponse: Contains the user’s payment details.
- console.log(paymentResponse): Logs the payment response for processing.
- catch((error) => { ... }): If the payment fails or is canceled, this promise catches the error and logs it.
Summary
This code manages a shopping cart by adding, removing, and updating items, and then processes a payment using the Payment Request API. If you have any more questions or need further clarification, feel free to ask in the comments!
Conclusion
That concludes my article about creating a shopping cart with payment integration in HTML5, CSS3, and JS! Make sure to leave a comment and a reaction and check out more of my stuff!
위 내용은 결제 통합을 통해 HTMLCSS 및 JS에서 간단한 장바구니를 만드는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Google Fonts가 새로운 디자인 (트윗)을 출시 한 것을 볼 수 있습니다. 마지막 큰 재 설계와 비교할 때 이것은 훨씬 더 반복적 인 느낌이 듭니다. 차이를 간신히 말할 수 있습니다

프로젝트에 카운트 다운 타이머가 필요한 적이 있습니까? 그런 것은 플러그인에 도달하는 것이 당연하지만 실제로는 훨씬 더 많습니다.

요소 수가 고정되지 않은 경우 CSS를 통해 지정된 클래스 이름의 첫 번째 자식 요소를 선택하는 방법. HTML 구조를 처리 할 때 종종 다른 요소를 만듭니다 ...

플렉스 레이아웃의 보라색 슬래시 영역에 대한 질문 플렉스 레이아웃을 사용할 때 개발자 도구 (d ...)와 같은 혼란스러운 현상이 발생할 수 있습니다.

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

프론트 엔드 개발에서 Windows와 같은 구현 방법 ...

타탄은 일반적으로 스코틀랜드, 특히 세련된 킬트와 관련된 패턴의 천입니다. tartanify.com에서 우리는 5,000 개가 넘는 타탄을 모았습니다
