私は把握できないようなJavaScriptの更新機能を持っています。ドロップダウンが更新されると2回発射されているように見えるので、そこにはいけない余分なコストが追加されます。JavaScriptで小計を正しく更新するにはどうすればよいですか?
は、ここに私の現在のコードです:
var updateTotal = function(option) {
var sumtotal;
var sum = 0;
// Add each product price to total
$(".product").each(function() {
var price = $(this).data('price');
var selector = document.getElementById('variety_weight');
var quantity = selector[selector.selectedIndex].value;
var ptotal = $(packaging).find('option:selected').val();
if (ptotal == 2) {
var burlap = 4.99;
var subburlap = quantity * burlap;
var subtotal = price * quantity + subburlap;
} else {
var subburlap = 0.00;
var subtotal = price * quantity;
}
// Round to 2 decimal places.
subtotal = subtotal.toFixed(2);
// Display subtotal in HTML element
$('.productTotal', this).html(subtotal);
});
// Total
$('.productTotal').each(function() {
sum += Number($(this).html());
});
sum = sum + 9.99;
$('#sum').html(sum.toFixed(2));
};
そして、私の最初のコードはこれです:
$('#variety_weight').change(function() {
/*
* Setting currently changed option value to option variable.
*/
var option = $(this).find('option:selected').val();
/*
* Setting input box value to selected option value.
*/
alert("Firing variety");
updateTotal();
});
$('#packaging').change(function() {
/*
* Setting currently changed option value to option variable.
*/
var option = $(this).find('option:selected').val();
alert(option);
/*
* Setting input box value to selected option value.
*/
alert("Firing packaging");
updateTotal(option);
});
// Set this from local
$('span.productTotal').each(function() {
$(this).before("")
});
// Unit price
$('.product p').each(function() {
var $price = $(this).parents("div").data('price');
$(this).before($price);
});
// Update totals when page first loads
updateTotal();
最終結果は、そのユーザーがパッケージングオプションを選択し、オプション2にそれを切り替えたとき - I 4.99単位で数量と時間をとり、それを小計に加えるようにしています。
しかし、最初のロードとupdateTotal()
関数はうまく動作しますが、パッケージ化オプションを選択してupdateTotal()
関数を2回呼び出しているように見える場合は、4.99ではなく9.98が追加されます。
htmlでも投稿できますか? – DinoMyte
IDパッケージには複数の要素がありますか? –
if-else条件の範囲内で変数を割り当てるのはなぜですか?後で使用する予定がある場合は、条件付きで宣言する必要があります。それはJavaScriptで動作するかもしれませんが、それは正しい、容認された方法ではありません。 –