所以我有一个重力形式来存储价格和产品变量。我有代码,因此当数量为 3 或更多时,它开始对每个长度的价格和总价格进行折扣,但是每个长度的折扣价格和总折扣价格仅显示一秒钟,然后恢复为非折扣价格。
您可以看到此内容的 URL 是 https://wordpress-714066-4065525.cloudwaysapps.com/product/custom-bunting/
所以我尝试过价格计算代码需要在创建总价变异函数中重复
我的代码是
//Get Custom Quantity Field
const customQuanityField = document.querySelector('.gfield--type-number input');
customQuanityField.value = 1;
//Get the default Quantity Field
const defaultQuanityField = document.querySelector('input[name="quantity"]');
defaultQuanityField.parentElement.setAttribute('style', 'display: none');
//defaultQuanityField.disabled = true;
let isProgrammaticChange = false;
defaultQuanityField.addEventListener('change', (e) => {
if (isProgrammaticChange) {
isProgrammaticChange = false;
return;
}
const quantity = e.target.value;
isProgrammaticChange = true;
customQuanityField.value = quantity;
});
customQuanityField.addEventListener('change', (e) => {
if (isProgrammaticChange) {
isProgrammaticChange = false;
return;
}
const quantity = e.target.value;
isProgrammaticChange = true;
defaultQuanityField.value = quantity;
});
//
//
//Custom Bunting Update price to read £xx.xx per car flag
//
//
// Select the node that will be observed for mutations
const dynamicPriceEl = document.querySelector('.product_totals ul > li:last-of-type > div');
const perFlagTextEl = document.createElement('p');
perFlagTextEl.textContent = ' per length';
perFlagTextEl.classList.add('per-length-text');
dynamicPriceEl.appendChild(perFlagTextEl);
// Options for the observer (which mutations to observe)
const config = { attributes: false, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const createTotalPrice = (mutationList, observer) => {
console.log('createTotalPrice');
for (const mutation of mutationList) {
if (mutation.type === "childList") {
const target = mutation.target;
const splitPrice = target.innerHTML.split('').slice(1).join('');
const calculatedPrice = parseFloat(splitPrice);
const totalPrice = (customQuanityField.value * calculatedPrice).toFixed(2);
console.log('totalPrice', totalPrice);
const totalPriceCalculation = document.querySelector('.total-calculated-price');
if(totalPriceCalculation) {
totalPriceCalculation.textContent = totalPrice;
} else {
const totalPriceCalculationEl = document.createElement('p');
totalPriceCalculationEl.classList.add('total-calculated-price');
totalPriceCalculationEl.textContent = totalPrice;
target.parentElement.after(totalPriceCalculationEl)
}
//console.log(`The new list has ${mutation.addedNodes[0].children[0].childElementCount} chilren.`);
}
}
};
// Create an observer instance linked to the callback function
const createTotalPriceObserver = new MutationObserver(createTotalPrice);
// Start observing the target node for configured mutations
createTotalPriceObserver.observe(dynamicPriceEl, config);
window.addEventListener('load', () => {
console.log('Script initialized');
// DOM Elements
const customQuanityField = document.querySelector('.gfield--type-number input');
const formattedTotalPrice = document.querySelector('.formattedTotalPrice');
const dynamicPriceEl = document.querySelector('.product_totals ul > li:last-of-type > div');
const gformPrice = document.querySelector('.ginput_product_price');
const gformTotal = document.querySelector('.ginput_total');
function updatePriceDisplay(quantity) {
if (!originalUnitPrice || isUpdating) return;
isUpdating = true;
try {
const discount = getDiscount(quantity);
const discountedUnitPrice = originalUnitPrice * (1 - discount / 100);
const total = discountedUnitPrice * quantity;
console.log('Calculating prices:', {
originalPrice: originalUnitPrice,
quantity,
discount,
discountedUnit: discountedUnitPrice,
total
});
// Update Gravity Forms price field and trigger recalculation
if (gformPrice) {
gformPrice.value = discountedUnitPrice.toFixed(2);
// Trigger multiple events to ensure Gravity Forms updates
gformPrice.dispatchEvent(new Event('change', { bubbles: true }));
gformPrice.dispatchEvent(new Event('keyup', { bubbles: true }));
// Force Gravity Forms to recalculate
if (window.gformCalculateTotalPrice) {
window.gformCalculateTotalPrice(1); // Assuming form ID is 1
}
// Update quantity field if it exists
const quantityInput = document.querySelector('input[name="quantity"]');
if (quantityInput) {
quantityInput.value = quantity;
quantityInput.dispatchEvent(new Event('change', { bubbles: true }));
}
}
// Update message
let messageEl = document.querySelector('.add-more-message');
if (!messageEl) {
messageEl = document.createElement('p');
messageEl.classList.add('add-more-message');
customQuanityField.after(messageEl);
}
messageEl.textContent = quantity < 3
? `Add ${3 - quantity} more to your basket to qualify for a 2.5% discount to this item.`
: `You're currently getting ${discount}% off this item.`;
// Force update total display
if (gformTotal) {
const newTotal = total.toFixed(2);
if (gformTotal.textContent !== `£${newTotal}`) {
gformTotal.textContent = `£${newTotal}`;
}
}
} finally {
isUpdating = false;
}
}
});
}
</script>
能够使用以下代码解决我的问题:
// Remove the discount from the price to get the true base price
const price = parseFloat(priceText.replace(/[^0-9.]/g, ''));
const quantity = parseInt(customQuanityField.value) || 1;
// Find current discount if any
let currentDiscount = 0;
for (const range in productDiscounts) {
const [min, max] = range.split(' - ').map(Number);
if (quantity >= min && quantity <= max) {
currentDiscount = productDiscounts[range];
break;
}
}
// Return the original base price by removing the discount
return price / (1 - currentDiscount / 100);
// Remove the discount from the price to get the true base price
const price = parseFloat(priceText.replace(/[^0-9.]/g, ''));
const quantity = parseInt(customQuanityField.value) || 1;
// Find current discount if any
let currentDiscount = 0;
for (const range in productDiscounts) {
const [min, max] = range.split(' - ').map(Number);
if (quantity >= min && quantity <= max) {
currentDiscount = productDiscounts[range];
break;
}
}
// Return the original base price by removing the discount
return price / (1 - currentDiscount / 100);