【问题标题】:Trying to replicate this jQuery template using handlebars尝试使用把手复制此 jQuery 模板
【发布时间】:2023-03-17 06:05:01
【问题描述】:

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

我正在尝试输出项目Price * Quantity,但无法正确附加项目的小计。当我将新商品添加到我的购物篮时,它会计算该商品的价格并将其显示为新元素,而不是将其添加到当前的总价格中。这可能是因为 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

我的车把计算助手 --

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));
    }

【问题讨论】:

    标签: javascript jquery handlebars.js


    【解决方案1】:

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

    相反,我创建了一个handlebar.helperfor() for totalPrice。

    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 }}

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      相关资源
      最近更新 更多