我有一个简单的项目,我通过js创建购物车。我遇到的问题是,第一次点击产品时,会返回“undefined”,第二次单击某个项目时,返回会查看单击的第一个项目的数据。 例如,如果我第一次点击培根,我得到未定义,然后我点击火腿我得到了培根的数据。
AddToOrder
function addToOrder(val) {
//if order does not exist than create it
if (typeof (Storage) !== "undefined") {
if (localStorage.getItem(val) === null) {
var qty = 1;
localStorage.setItem(val, qty);
console.log("New Product");
getPro(val);
console.log("Item is " + prod);
$("#order").append("<tr> <td>" + prod.Name + " </td> <td> € </td > <td><button class='btn btn-success' onClick='addToOrder()'>Remove From Cart</button></td> </tr > ");
}
else if (localStorage.getItem(val) !== null) {
var attempts = parseInt(localStorage.getItem(val));
localStorage.setItem(val, ++attempts);
console.log(attempts);
console.log("Existing Product");
localStorage.setItem("product", getPro(val));
console.log(localStorage.getItem("product"));
// console.log(pro + " " + localStorage.getItem(val));
}
}
//if product already in order add quantity only and remove stock
//removeOne(val); //Remove item from order
}
GetProduct
function getPro(id) {
$.getJSON(urlProducts + "/" + id, function (data) {
prod = JSON.stringify(data);
console.log(prod);
});
}