1
昨晚我剛剛遇到了句柄,它似乎是從您的javascript/jQuery代碼中分離出HTML模板的好方法。但我有一個問題在車把中複製一個簡單的代碼。試圖使用把手來複制這個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));
}