簡體   English   中英

需要使用 javascript/jQuery 從購物車中添加和刪除項目

[英]Need to add and delete items from a Shopping Cart using javascript/jQuery

我的家庭作業有問題。 我需要使用 Javascript、HTML5 和 JQuery 創建一個購物車,它必須將商店中的所有商品收集到一個數組中。 我想我幾乎解決了它,但我無法弄清楚如何將多個相同的項目添加到購物車而不在購物車列表上創建 2 個不同的對象。

另外,如果可能的話,我希望能夠直接從購物車中更改某些商品的數量,並可以選擇升級或降級數量。

這就是我目前正在做的事情:

 <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title></title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"> <script> window.onload = function () { // Variables var baseDeDatos = [ { id: 1, nombre: 'Jean Mom', precio: 1399 }, { id: 2, nombre: 'Pant Ren', precio: 990 }, { id: 3, nombre: 'Buzo Largo Hailey', precio: 948 }, { id: 4, nombre: 'Cycle Short', precio: 550 }, { id: 5, nombre: 'Top Cellie', precio: 590 }, { id: 6, nombre: 'Jacket Denim Ray', precio: 2890 }, { id: 7, nombre: 'Cinto Vice', precio: 499 }, { id: 8, nombre: 'Top Caro', precio: 499 }, { id: 9, nombre: 'Bra Top Regan', precio: 590 }, { id: 10, nombre: 'Sweater Polly', precio: 1399 }, { id: 11, nombre: 'Camisa June', precio: 799 }, { id: 12, nombre: 'Pant Amy', precio: 1299 }, { id: 13, nombre: 'Top Tai', precio: 648 }, { id: 14, nombre: 'Tapado Judy', precio: 3290 }, { id: 15, nombre: 'Mini Corderoy Lou', precio: 1090 } ] var $items = document.querySelector('#items'); var carrito = []; var total = 0; var $carrito = document.querySelector('#carrito'); var $total = document.querySelector('#total'); // Funciones function renderItems () { for (var info of baseDeDatos) { // Estructura var miNodo = document.createElement('div'); miNodo.classList.add('card', 'col-sm-4'); // Body var miNodoCardBody = document.createElement('div'); miNodoCardBody.classList.add('card-body'); // Titulo var miNodoTitle = document.createElement('h5'); miNodoTitle.classList.add('card-title'); miNodoTitle.textContent = info['nombre']; // Precio var miNodoPrecio = document.createElement('p'); miNodoPrecio.classList.add('card-text'); miNodoPrecio.textContent = '$' +info['precio']; // Boton var miNodoBoton = document.createElement('button'); miNodoBoton.classList.add('btn', 'btn-primary'); miNodoBoton.textContent = '+'; miNodoBoton.setAttribute('marcador', info['id']); miNodoBoton.addEventListener('click', anyadirCarrito); // Insertamos miNodoCardBody.appendChild(miNodoTitle); miNodoCardBody.appendChild(miNodoPrecio); miNodoCardBody.appendChild(miNodoBoton); miNodo.appendChild(miNodoCardBody); $items.appendChild(miNodo); } } function anyadirCarrito () { // Anyadimos el Nodo a nuestro carrito carrito.push(this.getAttribute('marcador')) // Calculo el total calcularTotal(); // Renderizamos el carrito renderizarCarrito(); } function renderizarCarrito () { // Vaciamos todo el html $carrito.textContent = ''; // Generamos los Nodos a partir de carrito carrito.forEach(function (item, indice) { // Obtenemos el item que necesitamos de la variable base de datos var miItem = baseDeDatos.filter(function(itemBaseDatos) { return itemBaseDatos['id'] == item; }); // Creamos el nodo del item del carrito var miNodo = document.createElement('li'); miNodo.classList.add('list-group-item', 'text-right'); miNodo.textContent = `${miItem[0]['nombre']} - $${miItem[0]['precio']}`; // Boton de borrar var miBoton = document.createElement('button'); miBoton.classList.add('btn', 'btn-danger', 'mx-5'); miBoton.textContent = 'X'; miBoton.setAttribute('posicion', indice); miBoton.addEventListener('click', borrarItemCarrito); // Mezclamos nodos miNodo.appendChild(miBoton); $carrito.appendChild(miNodo); }) } function borrarItemCarrito () { // Obtenemos la posicion que hay en el boton pulsado var posicion = this.getAttribute('posicion'); // Borramos la posicion que nos interesa carrito.splice(posicion, 1); // volvemos a renderizar renderizarCarrito(); // Calculamos de nuevo el precio calcularTotal(); } function calcularTotal () { // Limpiamos precio anterior total = 0; // Recorremos el array del carrito for (var item of carrito) { // De cada elemento obtenemos su precio var miItem = baseDeDatos.filter(function(itemBaseDatos) { return itemBaseDatos['id'] == item; }); total = total + miItem[0]['precio']; } // Formateamos el total para que solo tenga dos decimales var totalDosDecimales = total.toFixed(2); // Renderizamos el precio en el HTML $total.textContent = totalDosDecimales; } // Eventos // Inicio renderItems(); } </script> </head> <body> <div class="container"> <div class="row"> <!-- Elementos generados a partir del JSON --> <main id="items" class="col-sm-8 row"></main> <!-- Carrito --> <aside class="col-sm-4"> <h2>Carrito</h2> <!-- Elementos del carrito --> <ul id="carrito" class="list-group"></ul> <hr> <!-- Precio total --> <p class="text-right">Total: <span id="total"></span>&dollar;</p> </aside> </div> </div> </body> </html>

哦,我真的不知道如何在我的代碼中實現 jQuery,所以任何建議都會非常有幫助!

您可以添加輸入數量,示例如下:

function renderizarCarrito() {
  // Vaciamos todo el html
  $carrito.textContent = '';
  // Generamos los Nodos a partir de carrito
  arrayCart.forEach(function (item, indice) {
    // Obtenemos el item que necesitamos de la variable base de datos
    // Creamos el nodo del item del carrito
    var miNodo = document.createElement('li');
    var inputCantidad = document.createElement('input');
    inputCantidad.setAttribute('type', 'number');
    inputCantidad.setAttribute('min', '0');
    inputCantidad.setAttribute('max', '10');
    inputCantidad.setAttribute('value', arrayCart[indice]['cantidad']);
    inputCantidad.classList.add('input-list');
    miNodo.classList.add('list-group-item', 'text-right');
    miNodo.textContent = `${arrayCart[indice]['nombre']} - $${arrayCart[indice]['precio']} - `;
    // Boton de borrar
    var miBoton = document.createElement('button');
    miBoton.classList.add('btn', 'btn-danger', 'mx-5');
    miBoton.textContent = 'X';
    miBoton.setAttribute('posicion', indice);
    miBoton.addEventListener('click', borrarItemCarrito);
    // Mezclamos nodos

    miNodo.appendChild(inputCantidad);
    miNodo.appendChild(miBoton);
    $carrito.appendChild(miNodo);
  })
}

你會得到:

在此處輸入圖片說明

我只能在這里幫助你,問候。

你有唯一的 id 對嗎?所以,在判斷 item.id 是否已經在購物車之前添加項目

一些快速的 jQuery 指針:

  1. 您缺少 jQuery 和 bootstrap javascript 文件。 您只包含了引導程序 CSS 文件 - 因此您的頁面中實際上沒有jQuery,或者大部分引導程序(一些引導程序可以工作,這會令人困惑)。 解決方法:在你的腦海中,替換這一行:
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">

用這四行:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  1. jQuery 提示:將這個: window.onload = function () {替換為
    $(document).ready(function(){
  1. jQuery 提示:將這個: document.querySelector替換為: $
    Example FROM:  document.querySelector('#items');
              TO:  $('#items');
  1. 使用 jQuery .on() - 當頁面第一次創建(“渲染”)時,javascript 會立即運行。 如果某些 js 代碼在創建元素之前運行將事件偵聽器綁定到元素,則不會附加該事件偵聽器! 我們使用document.ready來解決這個問題。 document.ready說,“延遲運行此函數內的所有代碼(即,在 document.ready 函數代碼塊內),直到所有 HTML 元素都已呈現(創建並放置在頁面上)”。

但一個類似的問題是如何將事件偵聽器附加到稍后添加到頁面的元素——而 jQuery .on()就是你這樣做的方式。 基本上,您從一開始就添加一個 jQuery .on()功能塊,稍后,當這些元素之一添加到 DOM 時,事件處理程序將即時附加。 這就是我們喜歡 jQuery 的原因 #47。

  1. 作為約定/傳統(不是規則),我們通常用$前綴變量,即 jQuery 對象 在變量名中, $不做任何事情,它只是提醒我們這是一個 jQuery 對象,我們可以直接在它上面使用 jQuery 方法/屬性。

StackOverflow 的目的是幫助,而不是為你編寫 因此,本着這種精神,我將您的 js 變成了 jQuery。 如果您仔細查看它,您會發現它正是您所寫的 - 只是切換到 jQuery。

現在你的工作是讓代碼工作。 並非我所做的一切都已完成/正在工作。 每一行仍然需要審查/測試/調整。 但至少現在你可以開始了。

請注意,我添加了debugger;這個詞debugger; 到您的 javascript。 如果您在 Google Chrome 中進行測試——並且如果您打開了 DevTools(按F12 )——那么debugger語句將允許您逐行執行代碼。 這是您將找到的最好的工具,可以弄清楚如何使其工作。

非工作堆棧片段:

 $(document).ready(function() { // Variables debugger; var baseDeDatos = [ { id: 1, nombre: 'Jean Mom', precio: 1399 }, { id: 2, nombre: 'Pant Ren', precio: 990 }, { id: 3, nombre: 'Buzo Largo Hailey', precio: 948 }, { id: 4, nombre: 'Cycle Short', precio: 550 }, { id: 5, nombre: 'Top Cellie', precio: 590 }, { id: 6, nombre: 'Jacket Denim Ray', precio: 2890 }, { id: 7, nombre: 'Cinto Vice', precio: 499 }, { id: 8, nombre: 'Top Caro', precio: 499 }, { id: 9, nombre: 'Bra Top Regan', precio: 590 }, { id: 10, nombre: 'Sweater Polly', precio: 1399 }, { id: 11, nombre: 'Camisa June', precio: 799 }, { id: 12, nombre: 'Pant Amy', precio: 1299 }, { id: 13, nombre: 'Top Tai', precio: 648 }, { id: 14, nombre: 'Tapado Judy', precio: 3290 }, { id: 15, nombre: 'Mini Corderoy Lou', precio: 1090 } ] var $items = $('#items'); var carrito = []; var total = 0; var $carrito = $('#carrito'); var $total = $('#total'); //Use jQuery .on() method to attach an event handler to ALL FUTURE such elements $(document).on('click', 'button.item-button', function(){ debugger; $this = $(this); anyadirCarrito($this) }); $(document).on('click', 'carr-button', function(){ $this = $(this); borrarItemCarrito($this); }); // Funciones function renderItems () { for (var info of baseDeDatos) { // Estructura var $miNodo = $('div'); miNodo.addClass('card', 'col-sm-4'); // Body var $miNodoCardBody = $('div'); miNodoCardBody.addClass('card-body'); // Titulo var $miNodoTitle = $('h5'); $miNodoTitle.addClass('card-title'); $miNodoTitle.text(info['nombre']); // Precio var $miNodoPrecio = $('p'); $miNodoPrecio.addClass('card-text'); $miNodoPrecio.text('$' + info['precio']); // Boton var $miNodoBoton = $('button'); $miNodoBoton.addClass('btn', 'btn-primary', 'item-button'); $miNodoBoton.text('+'); $miNodoBoton.attr('marcador', info['id'])); // Insertamos $miNodoCardBody.append($miNodoTitle); $miNodoCardBody.append($miNodoPrecio); $miNodoCardBody.append($miNodoBoton); $miNodo.append($miNodoCardBody); $items.append($miNodo); } } function anyadirCarrito ($this) { // Anyadimos el Nodo a nuestro carrito carrito.push($this.getAttribute('marcador')) // Calculo el total calcularTotal($this); // Renderizamos el carrito renderizarCarrito($this); } function renderizarCarrito ($this, carrito) { //What is "carrito" and where is it created? It needs to be added to the fn call // Vaciamos todo el html carrito.text(); //clear it // Generamos los Nodos a partir de carrito carrito.forEach(function (item, indice) { // Obtenemos el item que necesitamos de la variable base de datos var miItem = baseDeDatos.filter(function(itemBaseDatos) { return itemBaseDatos['id'] == item; }); // Creamos el nodo del item del carrito var $miNodo = $('li'); $miNodo.addClass('list-group-item', 'text-right'); let summat = `${miItem[0]['nombre']} - $${miItem[0]['precio']}`; $miNodo.text(summat); // Boton de borrar var $miBoton = $('button'); $miBoton.addClass('btn', 'btn-danger', 'mx-5', 'carr-button'); $miBoton.text('X'); $miBoton.attr('posicion', indice); // Mezclamos nodos $miNodo.append($miBoton); carrito.append($miNodo); }); } function borrarItemCarrito ($this, carrito) { // Obtenemos la posicion que hay en el boton pulsado var posicion = $this.attr('posicion'); // Borramos la posicion que nos interesa carrito.splice(posicion, 1); // volvemos a renderizar renderizarCarrito($this, carrito); // Calculamos de nuevo el precio calcularTotal($this); } function calcularTotal () { // Limpiamos precio anterior total = 0; // Recorremos el array del carrito for (var item of carrito) { // De cada elemento obtenemos su precio var miItem = baseDeDatos.filter(function(itemBaseDatos) { return itemBaseDatos['id'] == item; }); total = total + miItem[0]['precio']; } // Formateamos el total para que solo tenga dos decimales var totalDosDecimales = total.toFixed(2); // Renderizamos el precio en el HTML // ERROR var total is not an html element, is it? You can only use `.text()` (and .textContent) on an ELEMENT $total.textContent = totalDosDecimales; } // Eventos // Inicio renderItems(); }
 <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title></title> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <!-- Elementos generados a partir del JSON --> <main id="items" class="col-sm-8 row"></main> <!-- Carrito --> <aside class="col-sm-4"> <h2>Carrito</h2> <!-- Elementos del carrito --> <ul id="carrito" class="list-group"></ul> <hr> <!-- Precio total --> <p class="text-right">Total: <span id="total"></span>&dollar;</p> </aside> </div> </div> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM