尝试使用把手复制这个jQuery模板

时间:2017-03-03 16:13:05

标签: javascript jquery handlebars.js

我昨晚刚遇到把手,这似乎是将HTML模板与javascript / jQuery代码分开的好方法。但我在手把中复制一个简单的小代码时遇到了问题。

我试图输出项目Price * Quantity,我无法正确追加项目的小计。当我向我的购物篮添加新商品时,它会计算该商品的价格并将其显示为新元素,而不是将其添加到当前的totalPrice中。这可能是因为subTotal中的{{#each this }}再次迭代了这些项目。

<div class="panel panel-default">
<div class="panel-body">
      <div class="row">
         {{#each this}}
         <div class="col-sm-8">{{ Quantity }} {{ Product }}</div>
         <div class="col-sm-4" style="text-align: right;">{{ Price }}</div>
         {{/each}}
      </div>
   </div>
   <div class="panel-footer">
      <h4 style="text-align: right;">
         Subtotal:
         {{#each this}}
         <span class="total">{{calculate Price "*" Quantity}}</span>
         {{/each}} 
      </h4>
   </div>
</div>

这是我的问题 - 应该是3.98 enter image description here

我的车把计算助手 -

Handlebars.registerHelper('calculate', function (priceVal, operator, quantity) {
        priceVal = parseFloat(priceVal);
        quantity = parseFloat(quantity);
        return {
            "+": priceVal + quantity,
            "-": priceVal - quantity,
            "*": priceVal * quantity,
            "/": priceVal / quantity,
            "%": priceVal % quantity
        }[operator];
    })

我想在手把中复制的jQuery模板

 for (product in cartItems) {
        html += '<div class="row" style="padding-bottom: 5px;">';
        html += '<div class="col-sm-12">';
        html += '<div class="col-sm-8">' + cartItems[product].Quantity + cartItems[product].Product + '</div>';
        html += '<div class="col-sm-4" style="text-align: right;">' + parseFloat(cartItems[product].Price).toFixed(2) + '</div>';
        html += '</div> </div>';
        var priceInt = parseFloat(cartItems[product].Price);
        var quantityInt = parseFloat(cartItems[product].Quantity);
        totalPrice += priceInt * quantityInt || 0;
        $('.total').text(totalPrice.toFixed(2));
    }

1 个答案:

答案 0 :(得分:0)

找到我的答案,但如果其他人有更好的想法,请分享

相反,我使用handlebar.helper为totalPrice创建了for()

Handlebars.registerHelper('subTotal', function () {
        var totalPrice = 0;
        for (product in cartItems) {
            var priceInt = parseFloat(cartItems[product].Price);
            var quantityInt = parseFloat(cartItems[product].Quantity);
            totalPrice += priceInt * quantityInt || 0;
        }
        if(totalPrice != 0){
            return totalPrice;
        }
    })

HTML - {{ subTotal }}