[英]Display Correct Radio Button Value Not Working with Default Checked Option?
问题:应用程序上显示默认选中的单选按钮值,但如果我更改提示值,然后取消选择并重新选择复选框,它会返回到原始选中的单选按钮值,而不是更改为新的提示值。
基本上,我的默认单选按钮值设置为$5
。 如果我选择了一个复选框选项,那么我将提示值更改为$2
然后取消选择一个复选框,然后重新选择一个复选框,它将提示值显示为$5
而不是新选项$2
这是我的代码笔。 我在 codepen 上添加了说明,这样你就可以看到我的问题
https://codepen.io/jaysomo10/pen/dydaKwZ
这是我的 JS
window.menuItems = 0;
window.tips = 0;
const foodTotal = document.getElementById("price");
const tipTotal = document.getElementById("tip");
const orderTotal = document.getElementById("total");
let tipVal = document.querySelector(".tips:checked").value;
tipTotal.textContent = "$" + (tipVal / 100).toFixed(2);
document.addEventListener("click", ({ target }) => {
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
window.tips = tipVal;
} else if (target.className === "food" && !target.checked) {
window.menuItems -= parseInt(target.value);
} else if (target.className === "tips" && target.checked) {
window.tips = parseInt(target.value);
} else {
return;
}
foodTotal.textContent = `$${(window.menuItems / 100).toFixed(2)}`;
tipTotal.textContent = `$${(window.tips / 100).toFixed(2)}`;
orderTotal.textContent = `$${(
(Number(window.menuItems) + Number(window.tips)) /
100
).toFixed(2)}`;
});
在我取消选择并重新选择复选框选项后,我似乎无法转换逻辑以更改提示值。
tipVal 是在点击事件之外定义的。 因此,它始终具有 sart 的价值。 您还必须在活动中更改它
window.menuItems = 0;
window.tips = 0;
const foodTotal = document.getElementById("price");
const tipTotal = document.getElementById("tip");
const orderTotal = document.getElementById("total");
let tipVal = document.querySelector(".tips:checked").value;
tipTotal.textContent = "$" + (tipVal / 100).toFixed(2);
document.addEventListener("click", ({ target }) => {
tipVal = document.querySelector(".tips:checked").value;
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
window.tips = tipVal;
} else if (target.className === "food" && !target.checked) {
window.menuItems -= parseInt(target.value);
} else if (target.className === "tips" && target.checked) {
window.tips = parseInt(target.value);
} else {
return;
}
foodTotal.textContent = `$${(window.menuItems / 100).toFixed(2)}`;
tipTotal.textContent = `$${(window.tips / 100).toFixed(2)}`;
orderTotal.textContent = `$${(
(Number(window.menuItems) + Number(window.tips)) /
100
).toFixed(2)}`;
});
从你的第一个 if 语句中删除它
if (target.className === "food" && target.checked && tipVal) {
window.menuItems += parseInt(target.value);
//window.tips = tipVal; // remove this
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.