我的购物车中有柜台,但我一直在努力使控件仅定位到我所在的特定柜台。相反,它将全部更新。
// Product Counter
DecreaseCount = function(){
var count = $(".quantity__count").val();
if (count > 0) count--;
if (count == 0) count = 0;
$(".quantity__count").val(count);
}
IncreaseCount = function(){
var count = $('.quantity__count').val();
if (count < 99) count++;
if (count == 99) count = 99;
$('.quantity__count').val(count);
}
// Does both
$('.quantity__decrement').click(function(){
DecreaseCount();
});
$('.quantity__increment').click(function(){
IncreaseCount();
});
// What I've tried
//$('.quantity__decrement').each(function(){
// $(this).on("click", function(){
// debugger;
// var count = $(".quantity__count").val();
// if (count > 0) count--;
// if (count == 0) count = 0;
// $(".quantity__count").val(count);
// });
//});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="o-grid o-grid--no-gutter">
<div class="quantity o-grid__cell">
<div class="quantity__decrement">-</div>
<input type="num" class="quantity__count" value="0" />
<div class="quantity__increment">+</div>
</div>
</div>
<div class="o-grid o-grid--no-gutter">
<div class="quantity o-grid__cell">
<div class="quantity__decrement">-</div>
<input type="num" class="quantity__count" value="0" />
<div class="quantity__increment">+</div>
</div>
</div>
我试过使用.closest,.siblings等;我有些困惑,我知道这不是一件棘手的事情。
任何帮助表示赞赏!
最佳答案
您可以使用一个函数来执行此操作,然后将clicked元素传递并更改类型作为参数。然后,在基于更改参数的函数内部,您可以从count
值中添加或减去。
ChangeCount = function(el, change) {
var count = el.siblings(".quantity__count").val();
change == "add" ? count++ : count--;
if (count < 0) count = 0;
if (count > 99) count = 99
el.siblings(".quantity__count").val(count);
}
$('.quantity > div').click(function() {
const change = $(this).hasClass('quantity__decrement') ? 'sub' : 'add';
ChangeCount($(this), change)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="o-grid o-grid--no-gutter">
<div class="quantity o-grid__cell">
<div class="quantity__decrement">-</div>
<input type="num" class="quantity__count" value="0">
<div class="quantity__increment">+</div>
</div>
</div>
<div class="o-grid o-grid--no-gutter">
<div class="quantity o-grid__cell">
<div class="quantity__decrement">-</div>
<input type="num" class="quantity__count" value="0">
<div class="quantity__increment">+</div>
</div>
</div>