如何在小费计算器的submit提交函数中获取点击选中的小费按钮数值
问题核心原因
- 你把小费按钮的点击监听放在了表单提交回调里,只有用户提交一次后按钮点击才会生效,逻辑顺序错误
- 没有变量存储用户选中的小费比例,点击按钮拿到的值无法被后续计算逻辑读取
- 原总费用计算逻辑错误,没有把人均小费加到人均账单里
- 没有做按钮选中态切换、按钮和自定义小费输入的互斥逻辑
修复后的完整JS代码
const form = document.getElementById("form"); const tipButtons = document.querySelectorAll(".tip-btn"); const tipInput = document.getElementById("tip-input"); // 全局变量存储选中的小费比例 let selectedTipPercent = 0; // 小费按钮点击逻辑 全局绑定 tipButtons.forEach(btn => { btn.addEventListener("click", e => { // 清除所有按钮选中态 tipButtons.forEach(b => b.classList.remove("active")); // 给当前点击按钮加选中态(你可以自己在css里写.active的样式区分选中状态) e.target.classList.add("active"); // 保存选中的比例 selectedTipPercent = Number(e.target.value); // 清空自定义小费输入,实现互斥 tipInput.value = ""; }) }) // 监听自定义小费输入,和按钮选中互斥 tipInput.addEventListener("input", e => { // 清除按钮选中态 tipButtons.forEach(b => b.classList.remove("active")); // 保存用户输入的比例 selectedTipPercent = Number(e.target.value) || 0; }) const submitHandler = (e) => { e.preventDefault(); const billValue = Number(document.getElementById("bill").value) || 0; const peopleCount = Number(document.getElementById("peopleNum").value) || 1; const tipAmountEl = document.getElementById("tip-amount"); const totalEl = document.getElementById("total"); // 计算人均账单 const billPerPerson = (billValue / peopleCount).toFixed(2); // 计算人均小费 用之前保存的selectedTipPercent const tipPerPerson = ((selectedTipPercent / 100) * billPerPerson).toFixed(2); // 计算人均总费用 = 人均账单 + 人均小费 const totalPerPerson = (Number(billPerPerson) + Number(tipPerPerson)).toFixed(2); tipAmountEl.innerHTML = `<span>$</span>${tipPerPerson}`; totalEl.innerHTML = `<span>$</span>${totalPerPerson}`; } // 事件监听 form.addEventListener("submit", submitHandler);
补充说明
你可以在css文件里加选中按钮的样式,方便用户识别:
.tip-btn.active { background-color: #26c2ae; color: #00474b; }
现在的逻辑是:用户点击按钮选小费比例,或者直接输入自定义比例,两个操作互斥,提交表单的时候会自动读取已经保存的小费比例做计算,完全符合你的需求。
内容的提问来源于stack exchange,提问作者TheRealJohnDoe
相关产品推荐
相关产品推荐

