1

我有一个选择字段供用户将 T 恤添加到他们的订单中。选项如下所示:

  • 没有 T 恤 ( value="no")
  • 小 ( value="S")
  • 中 ( value="M") ...等。

我目前将我的 JS 设置为:

$("select[name='tshirtsize']").change(function(){
    if($(this).val() == "no"){
        // subtract $15 from subtotal
    } else {
        // add $15 to subtotal
    }
});

但是,如果用户选择了一种衬衫尺码,然后更改为不同的衬衫尺码,则似乎将另一件衬衫添加到他们的购物车中,而不是替换第一件。这是有道理的,因为它应该以这种方式运行;但是,我不希望它。

我要做的是仅在用户小计中添加 15 美元,前提是他们从value="no"变为value="shirt-size-here",而不是在衬衫尺码之间。

想法?

4

5 回答 5

2

只要有一个变量来定义你是否已经没有

var none_selected = true; //change this based on whatever the default is
$("select[name='tshirtsize']").change(function(){
    if($(this).val() == "no"){
        // subtract $15 from subtotal
        none_selected = true;
    } else if (none_selected) {
        // add $15 to subtotal
        none_selected = false;
    }
});
于 2013-07-03T14:28:10.343 回答
0

您可以添加一个变量来存储选择的选项,如下所示:

tmpSelection = "no";
$("select[name='tshirtsize']").change(function(){
   if($(this).val() == "no"){
      // subtract $15 from subtotal
   } 
   else if(tmpSelection != "no" && $(this).val() != "no") {
    // add $15 to subtotal
   }
   tmpSelection = $(this).val();
});
于 2013-07-03T14:30:31.930 回答
0
var base_price = X;
$("select[name='tshirtsize']").change(function(){
    if($(this).val() != "no"){
        var new_price = base_price + Y;
        // update price to show user.
    }
});
于 2013-07-03T14:30:40.217 回答
0

对我来说最简单的解决方案似乎是在点击事件之外存储一个 hasTShirt 布尔值。另一种选择是在 selector.select() 事件上获取选择器的先前值,但它只涉及存储相同数量的数据......

例子:

var hasTshirt = 0; //0 = false, 1 = true    
  $("select[name='tshirtsize']").change(function(){
    if($(this).val() == "no" && hasTshirt == 1){
         hasTshirt = 0;
        // subtract $15 from subtotal
    } else if (hasTshirt == 0){
        hasTshirt = 1;
        // add $15 to subtotal
    }
});
于 2013-07-03T14:30:52.200 回答
0

无论变化(尺寸/颜色/等)是什么,您都需要创建一个特定于该产品价格的变量。

与其直接操纵总数,不如操纵特定产品的价格,然后将其添加到总数中。

$("select[name='tshirtsize']").change(function(){

    var price;

    if($(this).val() == "no"){
        shirtPrice = 0;
    } else {
        shirtPrice = 15;
    }

    var total = getTotal(); // Define these yourself
    setTotal(shirtPrice); // Define these yourself

});
于 2013-07-03T14:34:46.597 回答