찾다
웹 프론트엔드CSS 튜토리얼결제 통합을 통해 HTMLCSS 및 JS에서 간단한 장바구니를 만드는 방법

How to create a simple shopping cart in HTMLCSSand JS with Payment integration

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:



    <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">


    <div class="products">
        <div class="product">
            <h2 id="Product">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 id="Shopping-Cart">Shopping Cart</h2>
        <ul id="cart-items"></ul>
        <p>Total: $<span id="cart-total">0</span></p>
    </div>
    <script src="script.js"></script>


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

  1. 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

  1. 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
커서를위한 다음 레벨 CSS 스타일커서를위한 다음 레벨 CSS 스타일Apr 23, 2025 am 11:04 AM

CSS가있는 커스텀 커서는 훌륭하지만 JavaScript를 사용하여 다음 단계로 가져갈 수 있습니다. JavaScript를 사용하면 커서 상태를 전환하고 커서 내에 동적 텍스트를 배치하고 복잡한 애니메이션을 적용하며 필터를 적용 할 수 있습니다.

Worlds Collide : 스타일 쿼리를 사용한 KeyFrame Collision DetectionWorlds Collide : 스타일 쿼리를 사용한 KeyFrame Collision DetectionApr 23, 2025 am 10:42 AM

2025 년에 서로를 ricocheting하는 요소가있는 대화식 CSS 애니메이션은 CSS에서 Pong을 구현할 필요가 없지만 CSS의 유연성과 힘이 증가하는 것은 LEE의 의심을 강화합니다.

UI 효과를 위해 CSS 배경 필터 사용UI 효과를 위해 CSS 배경 필터 사용Apr 23, 2025 am 10:20 AM

CSS 배경 필터 속성을 사용하여 사용자 인터페이스 스타일에 대한 팁과 요령. 여러 요소들 사이에 필터를 배경으로 배경으로 배경으로하는 방법을 배우고 다른 CSS 그래픽 효과와 통합하여 정교한 디자인을 만듭니다.

미소?미소?Apr 23, 2025 am 09:57 AM

글쎄, SVG '의 내장 애니메이션 기능은 계획대로 이상 사용되지 않았다. 물론 CSS와 JavaScript는 부하를 운반 할 수있는 것 이상이지만 Smil이 이전과 같이 물에서 죽지 않았다는 것을 아는 것이 좋습니다.

'예쁜'은 보는 사람의 눈에 있습니다'예쁜'은 보는 사람의 눈에 있습니다Apr 23, 2025 am 09:40 AM

예, 텍스트-랩을위한 점프 : Safari Technology Preview의 예쁜 착륙! 그러나 Chromium 브라우저에서 작동하는 방식과는 다른 점을 조심하십시오.

CSS- 트릭 연대기 XLIIICSS- 트릭 연대기 XLIIIApr 23, 2025 am 09:35 AM

이 CSS- 트릭 업데이트는 Almanac, 최근 Podcast 출연, 새로운 CSS 카운터 가이드 및 귀중한 컨텐츠에 기여하는 몇 가지 새로운 저자의 추가 진전을 강조합니다.

Tailwind ' s @apply 기능은 소리보다 낫습니다Tailwind ' s @apply 기능은 소리보다 낫습니다Apr 23, 2025 am 09:23 AM

대부분의 경우 사람들은 Tailwind ' S 단일 프로퍼 유틸리티 중 하나 (단일 CSS 선언을 변경)와 함께 Tailwind ' s @apply 기능을 보여줍니다. 이런 식으로 선보일 때 @apply는 전혀 약속하는 소리가 들리지 않습니다. 그래서 Obvio

릴리스가없는 느낌 : 제정신 배치를 향한 여정릴리스가없는 느낌 : 제정신 배치를 향한 여정Apr 23, 2025 am 09:19 AM

바보처럼 배포하는 것은 배포하는 데 사용하는 도구와 복잡성에 대한 보상과 복잡성이 추가됩니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.