알아낼 수없는 JavaScript 업데이트 기능이 있습니다. 드롭 다운이 업데이트되면 두 번 해고되는 것 같습니다. 그러면 그렇게해서는 안되는 추가 비용이 추가됩니다.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()
기능이 정상적으로 작동하는 동안에는 패키징 옵션이 선택된 경우에만함수를 두 번 호출하는 것처럼 보입니다. 단지 4.99 대신 9.98이 추가됩니다.
html을 게시 할 수도 있습니까? – DinoMyte
ID 포장재가있는 요소가 두 개 이상 있습니까? –
if-else 조건문의 범위 내에서 변수를 할당하는 이유는 무엇입니까? 나중에 사용하려는 경우 조건의 외부에 선언해야합니다. 자바 스크립트에서도 작동 할 수는 있지만 올바른 방법은 아닙니다. –