【发布时间】:2025-12-08 08:15:02
【问题描述】:
我有一个页面列出产品 - 每个产品都有一个添加到购物车按钮。使用按钮中的数据属性,我需要将 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,然后才能通过 post 发送数组。
$(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);
}
);
});
});
【问题讨论】:
-
能否显示$(this).attr("data-offerId")的返回值;