Javascript 尝试使用Handlebar复制此jQuery模板
我昨晚刚刚看到了一些Handlebar,这似乎是一种将HTML模板与javascript/jQuery代码分离的好方法。但我在handlebar中复制一个简单的小代码时遇到了问题 我试图输出项目Javascript 尝试使用Handlebar复制此jQuery模板,javascript,jquery,handlebars.js,Javascript,Jquery,Handlebars.js,我昨晚刚刚看到了一些Handlebar,这似乎是一种将HTML模板与javascript/jQuery代码分离的好方法。但我在handlebar中复制一个简单的小代码时遇到了问题 我试图输出项目Price*Quantity,在正确追加项目小计时遇到问题。当我向购物篮中添加一个新项目时,它会计算该项目的价格,并将其显示为一个新元素,而不是将其添加到当前的总价中。这可能是因为小计中的{{{each this}}再次遍历了这些项目 <div class="panel panel-default"
Price*Quantity
,在正确追加项目小计时遇到问题。当我向购物篮中添加一个新项目时,它会计算该项目的价格,并将其显示为一个新元素,而不是将其添加到当前的总价中。这可能是因为小计中的{{{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>
我想在Handlebar中复制的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));
}
for(cartItems中的产品){
html+='';
html+='';
html+=''+cartItems[product]。数量+cartItems[product]。product+'';
html+=''+parseFloat(cartItems[product].Price).toFixed(2)+'';
html+='';
var pricint=parseFloat(cartItems[product].Price);
var quantityInt=parseFloat(cartItems[product].Quantity);
总价+=价格整数*数量整数| 0;
$('.total').text(totalPrice.toFixed(2));
}
找到了我的答案,但如果其他人有更好的想法,请分享
相反,我用totalPrice的for()
创建了一个handlebar.helper
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}
找到了我的答案,但如果其他人有更好的想法,请与我分享
相反,我用totalPrice的for()
创建了一个handlebar.helper
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}