[英]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>$</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 指针:
<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>
window.onload = function () {
替换为 $(document).ready(function(){
document.querySelector
替换为: $
Example FROM: document.querySelector('#items');
TO: $('#items');
.on()
- 当页面第一次创建(“渲染”)时,javascript 会立即运行。 如果某些 js 代码在创建元素之前运行将事件侦听器绑定到元素,则不会附加该事件侦听器! 我们使用document.ready
来解决这个问题。 document.ready
说,“延迟运行此函数内的所有代码(即,在 document.ready 函数代码块内),直到所有 HTML 元素都已呈现(创建并放置在页面上)”。 但一个类似的问题是如何将事件侦听器附加到稍后添加到页面的元素——而 jQuery .on()
就是你这样做的方式。 基本上,您从一开始就添加一个 jQuery .on()
功能块,稍后,当这些元素之一添加到 DOM 时,事件处理程序将即时附加。 这就是我们喜欢 jQuery 的原因 #47。
$
前缀变量,即 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>$</p> </aside> </div> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.