【问题标题】:Need to add and delete items from a Shopping Cart using javascript/jQuery需要使用 javascript/jQuery 从购物车中添加和删除项目
【发布时间】:2019-12-04 06:32:15
【问题描述】:

我的家庭作业有问题。我需要使用 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,所以任何建议都会非常有帮助!

【问题讨论】:

    标签: javascript jquery html shopping-cart


    【解决方案1】:

    你可以添加输入数量,这里是例子:

    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);
      })
    }
    

    你会得到:

    我只能在这里帮你,问候。

    【讨论】:

      【解决方案2】:

      你有唯一的 id 对吗?所以,在判断 item.id 是否已经在购物车中之前添加项目

      【讨论】:

        【解决方案3】:

        一些快速的 jQuery 指针:

        1. 您缺少 jQuery 和 bootstrap javascript 文件。您只包含了 bootstrap CSS 文件 - 所以您的页面中实际上并没有 jQuery,或者大部分 Bootstrap(一些 的 bootstrap 都可以工作,这会令人困惑)。解决方法:在你的脑海中,替换这一行:
            <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. 作为惯例/传统(不是规则),我们通常在variables-that-are-jQuery-objects 前加上$。在变量名中,$ 没有做任何事情,它只是提醒我们这是一个 jQuery 对象,我们可以直接在其上使用 jQuery 方法/属性。

        StackOverflow 的目的是协助,而不是为你编写。所以,本着这种精神,我把你的 js 变成了 jQuery。如果你仔细看,你会发现它正是你写的——只是切换到 jQuery。

        现在你的工作就是让代码工作。并非我所做的一切都已完成/工作。每一行仍然需要审查/测试/调整。但至少现在你可以开始了。

        请注意,我在您的 javascript 中添加了单词 debugger;。 IF 您正在 Google Chrome 中进行测试 -- IF 您打开了 DevTools(按 F12) -- THEN 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>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-13
          • 2013-01-11
          • 1970-01-01
          相关资源
          最近更新 更多