计算价格的脚本:
$(window).load(function(){
$('select').on('change', function(e) {
updateSubtotal();
updateDifferences();
});
function updateSubtotal() {
var subtotal = 0;
var start = 32;
$('.math1').each(function(i, el) {
subtotal += parseFloat($(this).find('option:selected').data('price')*start);
});
$('#display').text(subtotal);
};
function updateDifferences() {
$('.math1').each(function(i,sel) {
var $sel = $(sel);
$sel.find('option').each(function(j,opt) {
var $opt = $(opt),
optprice = $opt.data('price'),
selprice = $sel.find('option:selected').data('price'),
diff = optprice * selprice,
diffamount = Math.abs(diff) || "";
$opt.find('.diffaddsubtr').text(diffaddsubtr).end()
});
});
};
});
我在每个选择选项* 2编写器中使用data-price =" 2"它工作正常,直到它必须计算多个选择的价格:它会这样做
<select>
<option data-price="2">calculate total with *2</option><!--selected-->
<option data-price="5">calculate total with *5</option>
</select>
<select>
<option data-price="9">calculate total with *3</option><!--selected-->
<option data-price="3">calculate total with *9</option>
</select>
必须这样做32(= var start)*(3 * 2)= 192但它会这样做:32(= var start)*(2 + 3)= 160(=错误)如何解决此?
答案 0 :(得分:1)
您需要在updateSubtotal
function updateSubtotal() {
var subtotal = 32;
$('.math1').each(function(i, el) {
subtotal *= parseFloat($(this).find('option:selected').data('price'));
});
$('#display').text(subtotal);
};
答案 1 :(得分:0)
也许尝试类似的事情:
var totalMult = 0;
$('.math1').each(function(i, el) {
totalMult += parseFloat($(this).find('option:selected').data('price'));
});
subtotal = totalMult*start;