定价变化v2

时间:2015-04-16 16:16:56

标签: javascript jquery

好的,所以我昨天问了这个question,并根据我指出的方向进行了修改。当列表中有项目时,它按照我想要的方式工作,但是当它为0时,它会变为假,所以或者没有任何东西。当项目计数为0时,我不需要它显示0.00我知道0 = false这就是为什么或开始。任何帮助/解决方法?

var dropResult;
$(function (){
    $(".t").click(function(){
        dropResult = $("input[name=drop]:checked").val();
        dropCalculate();
    });
});

function dropCalculate() {
    var pricesObj = {
        '0':0,
        '1':450
      };
        var dropAmount = $(".itemadd", "#items").length;
        $("#dropAmount").html("Total: " + dropAmount);
        if (dropResult == 1) {
            dropTotal = (pricesObj[dropAmount] * dropAmount) || 450 + (150 * dropAmount - 150);
            $("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
        }else {
            dropTotal = (pricesObj[dropAmount] * dropAmount / 2) || 225 + (75 * dropAmount - 75);
            $("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
        }   
}

2 个答案:

答案 0 :(得分:1)

我以这种方式解决了我的问题。我不想走这条路,因为我觉得有一种更简单的方式。

var dropResult;
$(function (){
    $(".t").click(function(){
        dropResult = $("input[name=drop]:checked").val();
        dropCalculate();
    });
});

function dropCalculate() {
        var dropAmount = $(".itemadd", "#items").length;
        $("#dropAmount").html("Total: " + dropAmount);
        if (dropResult == 1 && dropAmount > 0) {
            dropTotal = 450 + (150 * (dropAmount -1));
            $("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
        }else if (dropAmount > 0) {
            dropTotal = 225 + (75 * (dropAmount -1));
            $("#dropPrice").html("Price Total: $" + dropTotal.toFixed(2));
        }else {
            $("#dropPrice").html("Price Total: $" + (0.00).toFixed(2));
        }   
}

答案 1 :(得分:1)

对于您不会立即遇到问题但可能会改进代码设计的问题,您可能会在Code Review Stack Exchange得到更好的回复。

以下代码应该与示例中的代码做同样的事情,但我认为它更具可读性。对于此用例而言,对象似乎不是必需的,但将来可能会有用。

同样,我应用了DRY Principle,这次我删除了Magic Numbers(代码中的数字没有明确的含义)。

var dropResult;
$(function (){
    $(".t").click(function(){
        dropResult = $("input[name=drop]:checked").val();
        dropCalculate(450);
    });
});

function dropCalculate(fullPrice) {
        var halfPrice = fullPrice / 2,
            quarterPrice = halfPrice / 2,
            dropAmount = $(".itemadd", "#items").length,
            finalPrice = 0.00;

        if(dropAmount > 0){
          if (dropResult === 1) {
             finalPrice = fullPrice; //the rest of this line was not necessary, as dropAmount - 1 is always 0 here.
          } else {
             finalPrice = halfPrice + (quarterPrice * (dropAmount - 1));
          }
        }

        $("#dropAmount").html("Total: " + dropAmount);
        $("#dropPrice").html("Price Total: $" + finalPrice.toFixed(2));
}
相关问题