快速提问-我有一个$ .each循环,在其中带有回调函数的函数调用
我可以在该回调函数中放入什么以继续循环
$.each(product, function () {
AddToCart($(this), function () {
});
});
现在-如果它遍历5个产品,则只有最后一个被添加到购物车
我需要一种暂停循环的方式,以确保在添加下一个产品之前将产品添加到购物车
谢谢!
这是AddToCart函数:
function AddToCart(product, callback) {
//Get the product ID and info
var product = product;
var productid = product.children(".productId").val();
var productName = product.children(".productName").val();
var productPage = product.children(".productPage").attr("href");
var productImage = product.find(".productImage").attr("src");
var productPrice = product.find(".productPrice").val();
var productMSRP = product.find(".productMSRP").val();
var productList = $("#productList");
var exists = false;
listItems = $("#productList").find("li");
// Loop through to see if the product has already been added
listItems.each(function (idx, li) {
var item = $(li);
var itemId = item.children(".productId").val();
if (itemId == productid) {
exists = true;
//find its quantity
var quantity = item.children(".quantity").html();
//increment the quantity
quantity = parseInt(quantity) + 1;
item.children(".quantity").html(quantity);
}
});
if (!exists) {
var listItem = "<li>" +
"<a href='" + productPage + "'><img height='80px' src='" + productImage + "'/></a>" +
"<input type='button' value='X' class='cartRemoveBtn'/>" +
"<span class='quantity'>1</span>" +
"<div class='tooltip_info'>" +
"<span class='tooltip_name'>" + productName + "</span>" +
"<span class='tooltip_price'>Our Price: $" + parseFloat(productPrice, 10).toFixed(2) + "</span>" +
"<span class='tooltip_msrp'>List Price: $" + parseFloat(productMSRP, 10).toFixed(2) + "</span>" +
"<span class='tooltip_savings'>You Save: $" + parseFloat(productMSRP - productPrice, 10).toFixed(2) + "</span>" +
"</div>" +
"<input type='hidden' class='productId' value='" + productid + "' />" +
"<input type='hidden' class='productPrice' value='" + productPrice + "' />" +
"<input type='hidden' class='productMSRP' value='" + productMSRP + "' />" +
"</li>";
productList.prepend(listItem);
}
OpenCart();
updateTotals();
initializeCart();
refreshTooltips();
$.post('/Store/Cart/AddToCart/' + productid, function () {
callback();
});
return false;
}
最佳答案
$ .each函数已经是同步的,这意味着它一次一次地逐步浏览每个产品。第一个函数调用将阻塞第二个函数调用,直到第一个函数返回。
这是一个工作的伪代码示例:
function AddToCart(item, callback){
alert(item);
};
var products = [1,2,3,4,5];
$.each(products, function(index, product){
AddToCart(product);
});
可能的问题
AddToCart函数在发布时注册一个回调(AddToCart内部的异步调用),这意味着它在发布函数有时间完成之前返回。我不知道您的回调函数在做什么,但这可能会在第一条帖子从“ / Store / Cart / AddToCart /”返回之前完成所有AddToCart调用。
解
运行取决于AddToCart函数的回调内部的帖子返回的代码。
替代解决方案
使用另一种形式逐步浏览产品...这使用AddToCart的回调调用下一个产品添加。
function AddEachToCart(products) {
// ensure products is not a js Array
products = $(products).toArray();
if (products.length > 0)
AddToCart(products.shift(), function(){AddEachToCart(products)});
};
关于javascript - 暂停Jquery.each循环以确保代码完全执行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4683738/