我有一个列出产品的页面-每个产品都有一个“添加到购物车”按钮。使用按钮中的data属性,我需要将offerId字符串推送到现有数组中。将多个产品添加到购物车后,预期结果将是返回一个包含所有offerId的数组。当前,如果我print_r offerIdArray,它仅显示最新按钮的offerId。
有什么想法吗?
$(document).ready(function () {
$(".addtocart button").click(function () {
var offerIdArray = [];
var offerId = $(this).attr("data-offerId");
$.post("controller/create-cart.php", {
offerIdArray: offerIdArray.push(offerId)
},
function (data) {
$('body').append(data);
});
});
});
编辑:以下是我的工作代码-感谢@brroshan。在通过邮寄发送数组之前,我还必须将offerId推送到offerIdArray。
$(document).ready(function () {
offerIdArray = [];
$(".addtocart button").click(function () {
var offerId = $(this).attr("data-offerId");
offerIdArray.push(offerId);
$.post("controller/create-cart.php",
{
offerIdArray: offerIdArray
},
function (data) {
$('body').append(data);
}
);
});
});
问题是您每次".addtocart button"
单击都会创建一个新数组。只需在点击处理程序外部声明数组即可,它应该可以正常工作。
$(document).ready(function () {
var offerIdArray = []; // <--
$(".addtocart button").click(function () {
var offerId = $(this).attr("data-offerId");
$.post("controller/create-cart.php", {
offerIdArray: offerIdArray.push(offerId)
},
function (data) {
$('body').append(data);
});
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句