@H_404_1@我从这里使用了入门代码:https://codepen.io/Dimasion/pen/oBoqBM.除了更改项目外,我什么都没做,现在添加到购物车不起作用.关于我需要做什么建议?我不了解发生了什么,因为一切基本相同.我已经包含了所有代码.预先感谢您的帮助!!!
@H_404_1@
const containerElement = document.querySelector('.container');
let items= [];
let template = `
{{#each items}}
<div class="row">
<div class="col">
<div class="card" style="width: 20rem;">
<img class="card-img-top" src="{{image}}" alt="Card image cap">
<div class="card-block">
<h4 class="card-title">{{title}}</h4>
<p class="card-text">Price: ${{price}}</p>
<a href="#" data-name="{{title}}" data-price="{{price}}" class="add-to-cart btn btn-primary">Add to cart</a>
</div>
</div>
</div>
</div>
{{/each}}
`;
function render(context) {
let compiled = Handlebars.compile(template);
containerElement.innerHTML = compiled(context);
}
$.ajax({
url: 'http://5ceb36a60c871100140bf873.mockapi.io/v1/item',method: 'GET'
}).done(function (resp) {
console.log(resp);
console.log(items);
items = {items : resp}
console.log(items);
render(items);
});
// ************************************************
// Shopping Cart API
// ************************************************
var shoppingCart = (function() {
// =============================
// Private methods and propeties
// =============================
cart = [];
// Constructor
function Item(name,price,count) {
this.name = name;
this.price = price;
this.count = count;
}
// Save cart
function saveCart() {
sessionStorage.setItem('shoppingCart',JSON.stringify(cart));
}
// Load cart
function loadCart() {
cart = JSON.parse(sessionStorage.getItem('shoppingCart'));
}
if (sessionStorage.getItem("shoppingCart") != null) {
loadCart();
}
// =============================
// Public methods and propeties
// =============================
var obj = {};
// Add to cart
obj.addItemToCart = function(name,count) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count ++;
saveCart();
return;
}
}
var item = new Item(name,count);
cart.push(item);
saveCart();
}
// Set count from item
obj.setCountForItem = function(name,count) {
for(var i in cart) {
if (cart[i].name === name) {
cart[i].count = count;
break;
}
}
};
// Remove item from cart
obj.removeItemFromCart = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart[item].count --;
if(cart[item].count === 0) {
cart.splice(item,1);
}
break;
}
}
saveCart();
}
// Remove all items from cart
obj.removeItemFromCartAll = function(name) {
for(var item in cart) {
if(cart[item].name === name) {
cart.splice(item,1);
break;
}
}
saveCart();
}
// Clear cart
obj.clearCart = function() {
cart = [];
saveCart();
}
// Count cart
obj.totalCount = function() {
var totalCount = 0;
for(var item in cart) {
totalCount += cart[item].count;
}
return totalCount;
}
// Total cart
obj.totalCart = function() {
var totalCart = 0;
for(var item in cart) {
totalCart += cart[item].price * cart[item].count;
}
return Number(totalCart.toFixed(2));
}
// List cart
obj.listCart = function() {
var cartCopy = [];
for(i in cart) {
item = cart[i];
itemCopy = {};
for(p in item) {
itemCopy[p] = item[p];
}
itemCopy.total = Number(item.price * item.count).toFixed(2);
cartCopy.push(itemCopy)
}
return cartCopy;
}
// cart : Array
// Item : Object/Class
// addItemToCart : Function
// removeItemFromCart : Function
// removeItemFromCartAll : Function
// clearCart : Function
// countCart : Function
// totalCart : Function
// listCart : Function
// saveCart : Function
// loadCart : Function
return obj;
})();
// *****************************************
// Triggers / Events
// *****************************************
// Add item
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = Number($(this).data('price'));
shoppingCart.addItemToCart(name,1);
displayCart();
});
// Clear items
$('.clear-cart').click(function() {
shoppingCart.clearCart();
displayCart();
});
function displayCart() {
var cartArray = shoppingCart.listCart();
var output = "";
for(var i in cartArray) {
output += "<tr>"
+ "<td>" + cartArray[i].name + "</td>"
+ "<td>(" + cartArray[i].price + ")</td>"
+ "<td><div class='input-group'><button class='minus-item input-group-addon btn btn-primary' data-name=" + cartArray[i].name + ">-</button>"
+ "<input type='number' class='item-count form-control' data-name='" + cartArray[i].name + "' value='" + cartArray[i].count + "'>"
+ "<button class='plus-item btn btn-primary input-group-addon' data-name=" + cartArray[i].name + ">+</button></div></td>"
+ "<td><button class='delete-item btn btn-danger' data-name=" + cartArray[i].name + ">X</button></td>"
+ " = "
+ "<td>" + cartArray[i].total + "</td>"
+ "</tr>";
}
$('.show-cart').html(output);
$('.total-cart').html(shoppingCart.totalCart());
$('.total-count').html(shoppingCart.totalCount());
}
// Delete item button
$('.show-cart').on("click",".delete-item",function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCartAll(name);
displayCart();
})
// -1
$('.show-cart').on("click",".minus-item",function(event) {
var name = $(this).data('name')
shoppingCart.removeItemFromCart(name);
displayCart();
})
// +1
$('.show-cart').on("click",".plus-item",function(event) {
var name = $(this).data('name')
shoppingCart.addItemToCart(name);
displayCart();
})
// Item count input
$('.show-cart').on("change",".item-count",function(event) {
var name = $(this).data('name');
var count = Number($(this).val());
shoppingCart.setCountForItem(name,count);
displayCart();
});
displayCart();
<!DOCTYPE html>
<html lang="en" >
<head>
<Meta charset="UTF-8">
<title>Shopping cart JS</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<link rel="stylesheet" href="index.css">
</head>
<body>
<!-- Nav -->
<nav class="navbar navbar-inverse bg-inverse fixed-top bg-faded">
<div class="row">
<div class="col">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#cart">Cart (<span class="total-count"></span>)</button><button class="clear-cart btn btn-danger">Clear Cart</button></div>
</div>
</nav>
<!-- Main -->
<div class="container"></div>
<!-- Modal -->
<div class="modal fade" id="cart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Cart</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="show-cart table">
</table>
<div>Total price: $<span class="total-cart"></span></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Order now</button>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.js"></script>
<script src="index.js"></script>
</body>
</html>
最佳答案
您说无法加入购物车,但是…您是否检查了是否正在调用JQuery单击处理程序?
@H_404_1@您的问题可能是由于获取和呈现项目的异步方式造成的:您在页面加载时对所有“ .add-to-cart”项目声明了单击处理程序,但目前没有任何元素,然后将它们加载.您应该在渲染函数后将所有引用DOM元素的逻辑包装在调用的函数中.就像是:
@H_404_1@
原文链接:https://www.f2er.com/html/530529.htmlfunction afterRender() {
$('.add-to-cart').click(function(event) {
event.preventDefault();
var name = $(this).data('name');
var price = Number($(this).data('price'));
shoppingCart.addItemToCart(name,1);
displayCart();
});
}
function render(context) {
let compiled = Handlebars.compile(template);
containerElement.innerHTML = compiled(context);
afterRender();
}