创建了一个函数,并希望将其转换为独立模块或正如您所说的OOP。
JavaScript / Jquery代码
(function(){
var el = $('#cartlist');
dataname = $(this).attr("data-name");
el.on('click', '.add-one', function(event){
shoppingCart.addIteamToCart(dataname, "description", 0, "image_url", 1);
displaylistCartItems();
});
el.on("click", ".delete-button", function(event){
shoppingCart.removeIteamFromCartAll(dataname);
displaylistCartItems();
});
el.on("click", ".delete-one", function(event){
shoppingCart.removeIteamFromCart(dataname);
displaylistCartItems();
});
$("#cartlist").on("change", ".item-count", function(event){
var count = Number($(this).val());
shoppingCart.setCountForItem(dataname, count);
});
})();
// JQuery
$(".add-to-cart").click(function(event){
event.preventDefault();
var title = $(this).attr("data-title");
var description = $(this).attr("data-description");
var price = Number($(this).attr("data-price"));
var image_url = $(this).attr("data-image_url");
shoppingCart.addIteamToCart(title, description, price, image_url, 1);
displaylistCartItems();
});
$("#clear-cart").click(function(event){
shoppingCart.clearCart();
displaylistCartItems();
});
function displaylistCartItems() {
var cartArray = shoppingCart.listCartItems();
var output = "";
for (var i in cartArray) {
output += "<li>"
+cartArray[i].title
+" <input class='item-count' style='height: 39px' type='number' data-name='"
+cartArray[i].title
+"' value='"+cartArray[i].count+"' >"
+" x "+cartArray[i].price
+" = "+cartArray[i].total
+" <button class='add-one' data-name='"+cartArray[i].title+"'>+</butto>"
+" <button class='delete-one' data-name='"+cartArray[i].title+"'>-</butto>"
+" <button class='delete-button' data-name='"
+cartArray[i].title+"'>X</button>"
+"</li>"
}
$("#cartlist").html(output);
$("#total-cart").html( shoppingCart.totalCart() );
console.log(shoppingCart.countCart());
$("#total-cart-count").html( shoppingCart.countCart() );
};
displaylistCartItems();
链接到plunker:https://plnkr.co/edit/IGpJiosj0siFBXcbLxsq?p=preview
答案 0 :(得分:0)
首先,您在第一个函数中传递一个变量,然后用另一个函数覆盖它,这就是导致您混淆的原因。
试试这个:
(function(){
var el = $('#cartlist');
var dataname = $(this).attr("data-name");
el.on('click', '.add-one', function(event){
shoppingCart.addIteamToCart(dataname, "description", 0, "image_url", 1);
displaylistCartItems();
});
el.on("click", ".delete-button", function(event){
shoppingCart.removeIteamFromCartAll(dataname);
displaylistCartItems();
});
el.on("click", ".delete-one", function(event){
shoppingCart.removeIteamFromCart(dataname);
displaylistCartItems();
});
})();
我不确定您要实现的目标,但每次触发对这些类的“点击”时,您都会覆盖相同的变量。