假设我有3个按钮的3个功能(+/-和“添加到购物车”)
结果(输入字段的值)被声明为全局变量,并在函数中更改
现在,要让我使用“添加到购物车”按钮将商品添加到购物车,该按钮将需要知道输入字段的值。
我的问题是这个
如果输入字段的值在第一和第二个函数中发生变化,我该如何访问?
虚拟代码:
let value;
$('.inc').on('click', function() {
value = 1;
});
$('.dec').on('click', function() {
value = 0;
});
$('.add-to-cart').on('click', function(){
// take value and send it to cart
});
注意:我已经用Google搜索了。要求将方向推向正确的方向。
let increaseValueBtn = $('button[data-action="inc"]');
let decreaseValueBtn = $('button[data-action="dec"]');
let newValue;
increaseValueBtn.on('click', function (event) {
event.preventDefault();
const productId = $(event.currentTarget).data('product-id');
const $el = $(`#qty-${productId}`);
const minQty = parseInt($el.data('quantity-min'), 10);
// updates value
newValue = $el.val(parseInt($el.val())+1);
// makes decrease btn clickable
if(newValue.val() > minQty) {
newValue.siblings(decreaseValueBtn).prop('disabled', false);
}
});
decreaseValueBtn.on('click', function (event) {
event.preventDefault();
const productId = $(event.currentTarget).data('product-id');
const $el = $(`#qty-${productId}`);
const minQty = parseInt($el.data('quantity-min'), 10);
// updates value
newValue = $el.val(parseInt($el.val())-1);
// if quantity is less than min qty than make decrease btn unclickable
if(newValue.val() == minQty) {
decreaseValueBtn.prop('disabled', true);
}
});
$('.card-btn').on('click', (event) => {
event.preventDefault();
var pro;
qty = 0;
const productId = $(event.currentTarget).data('product-id');
const minQty = $(event.currentTarget).data('min-qty');
const product_this = $(event.currentTarget);
pro = { "action": "add", "fastcart": "1", "product_id": productId, "qty[]": newValue };
qty += Number(newValue);
console.log(newValue.attr('value'));
//var check = checkBeforeAdd(pro);
// modal.open();
error = 0;
addToCart(pro);
// document.getElementById('modal').setAttribute('id', 'previewModal');
product_this.addClass('is-added');
product_this.find('span').text('Added');
setTimeout(function () {
product_this.removeClass('is-added');
product_this.find('span').text('Add');
}, 2500);
});