【发布时间】: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>
我的车把计算助手 --
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