无需点击按钮根据用户选择实时计算旅游产品订单价格的实现咨询
实现实时订单价格计算的方案
你只需要修改现有<script>标签内的JS代码即可完成需求,具体改动如下:
核心实现逻辑
- 封装独立的总价计算函数,统一处理规则判断、数值计算、结果渲染
- 在所有会影响价格的操作(增减人数、切换团型、切换ATV选项)触发时,自动调用计算函数更新总价
- 页面加载完成后自动计算初始价格,避免显示为空
完整修改后的JS代码
直接替换你现有页面里的<script>标签内容即可:
function increaseCount(e, el) { var input = el.previousElementSibling; var value = parseInt(input.value, 10); value = isNaN(value) ? 0 : value; value++; input.value = value; // 操作完成后更新总价 calculateTotal(); } function decreaseCount(e, el) { var input = el.nextElementSibling; var value = parseInt(input.value, 10); if (value > 1) { value = isNaN(value) ? 0 : value; value--; input.value = value; } // 操作完成后更新总价 calculateTotal(); } function decreaseCount2(e, el) { var input = el.nextElementSibling; var value = parseInt(input.value, 10); if (value > 0) { value = isNaN(value) ? 0 : value; value--; input.value = value; } // 操作完成后更新总价 calculateTotal(); } var MainImg = document.getElementById('MainImg'); var smallimg = document.getElementsByClassName('small-img'); smallimg[0].onclick = function() { MainImg.src = smallimg[0].src; } smallimg[1].onclick = function() { MainImg.src = smallimg[1].src; } smallimg[2].onclick = function() { MainImg.src = smallimg[2].src; } smallimg[3].onclick = function() { MainImg.src = smallimg[3].src; } // 新增:总价计算核心函数 function calculateTotal() { // 1. 获取所有参数 const adultCount = parseInt(document.querySelector('.counter1 input').value) || 0; const childCount = parseInt(document.querySelector('.counter2 input').value) || 0; const isPrivate = document.getElementById('private').checked; const hasAtv = document.getElementById('withatv').checked; // 2. 定义定价规则 let adultBasePrice, childBasePrice; if (isPrivate) { adultBasePrice = 100; childBasePrice = 50; } else { adultBasePrice = 40; childBasePrice = 30; } const adultAtvPrice = hasAtv ? 100 : 0; const childAtvPrice = hasAtv ? 80 : 0; // 3. 计算总价 const adultTotal = (adultBasePrice + adultAtvPrice) * adultCount; const childTotal = (childBasePrice + childAtvPrice) * childCount; const total = adultTotal + childTotal; // 4. 渲染到页面 document.querySelector('.total.Price').textContent = '$' + total; } // 新增:监听单选框切换事件,触发价格更新 document.querySelectorAll('input[name="occupancy"], input[name="atv"]').forEach(radio => { radio.addEventListener('change', calculateTotal); }); // 新增:页面加载完成后计算初始价格 window.addEventListener('load', calculateTotal);
效果说明
修改完成后,只要用户执行以下任意操作,总价都会实时更新:
- 增减成人/儿童人数
- 切换Private/Shared团型
- 切换是否包含ATV项目
完全不需要额外点击计算按钮,符合需求。
内容的提问来源于stack exchange,提问作者MMunir. Asif
相关产品推荐
相关产品推荐

