我有一个优惠券系统,无论何时创建新的订单明细,它都会将优惠券应用到标记为coupon_value的字段。我正在尝试介绍分层优惠券系统的想法,并试图弄清楚是否有某种方法来确定你所使用的.each()实例。
这是我的代码:
//Default value of the coupon is $200
coupon_value = 200;
//If there are 5 students or more the coupon value is $300
teir_value = 300;
//For each coupon_value set its html to the coupon value variable
$('.coupon_value').each(function(){
$(this).html('$' + coupon_value));
});
以下是我正在尝试做的事情:
学生1折优惠:200美元 学生2折优惠:200美元 学生3折优惠:200美元 学生4折优惠:200美元 学生5折优惠:300美元 学生6折优惠:300美元 ....
我是否可以在.each中说,如果这是渲染中的第5或更多类优惠券价值的实例,那么调整coupon_value = $ 300或只使用tier_value?
答案 0 :(得分:1)
您可以使用当前项目的索引来检查它是否是第5个或更多项目。 each()回调获取当前项的索引,将当前项作为2个参数。
//Default value of the coupon is $200
coupon_value = 200;
//If there are 5 students or more the coupon value is $300
teir_value = 300;
//For each coupon_value set its html to the coupon value variable
$('.coupon_value').each(function (i) {
$(this).html('$' + (i > 3 ? teir_value : coupon_value));
});
演示:Fiddle
正如您所使用的,如果您想引用循环中的当前项,您可以在每个处理程序中使用this
。