使用输入类型从复选框中删除事件监听器?
Remove Event Listener from Checkbox Using Input Type?
所以我有这个简单的事件侦听器,它会在我单击复选框时更新我的价格。
但是,我不知道如何重构我的逻辑以使其在取消选中复选框后减去价格?
let items = 0;
document.addEventListener("click", (e) => {
if (e.target.matches("input[type=checkbox]")) {
items += +e.target.value;
console.log(items);
document.getElementById("price").textContent = `Food Total: $${(
items / 100
).toFixed(2)}`;
}
});
到目前为止,此代码添加了我所有的复选框值,但如果我继续单击并取消单击它们,它们仍会将值添加到无穷大
也许您可以在单击复选框时添加 class“已选中”并在再次单击时将其删除?然后您可以使用 class 而不是原始点击事件。
我会将选中的框添加到集合中,然后 add/delete 单击时从集合中添加它们。检查它们是否已经在集合中,以确定您是否需要从总和中添加或减去。
const clickedCheckboxes = new Set();
let sum = 0;
const priceDiv = document.getElementById("price");
document.addEventListener("click", ({ target }) => {
if (!target.matches("input[type=checkbox]")) {
return;
}
if (clickedCheckboxes.has(target)) {
clickedCheckboxes.delete(target);
sum -= target.value;
} else {
clickedCheckboxes.add(target);
sum += Number(target.value);
}
priceDiv.textContent = `Food Total: $${(sum / 100).toFixed(2)}`;
});
我认为复选框应该有一个简单的布尔值 .checked 为真或假:https://www.w3schools.com/jsref/prop_checkbox_checked.asp
如果 .checked === false
,这可能允许您递减
所以我有这个简单的事件侦听器,它会在我单击复选框时更新我的价格。
但是,我不知道如何重构我的逻辑以使其在取消选中复选框后减去价格?
let items = 0;
document.addEventListener("click", (e) => {
if (e.target.matches("input[type=checkbox]")) {
items += +e.target.value;
console.log(items);
document.getElementById("price").textContent = `Food Total: $${(
items / 100
).toFixed(2)}`;
}
});
到目前为止,此代码添加了我所有的复选框值,但如果我继续单击并取消单击它们,它们仍会将值添加到无穷大
也许您可以在单击复选框时添加 class“已选中”并在再次单击时将其删除?然后您可以使用 class 而不是原始点击事件。
我会将选中的框添加到集合中,然后 add/delete 单击时从集合中添加它们。检查它们是否已经在集合中,以确定您是否需要从总和中添加或减去。
const clickedCheckboxes = new Set();
let sum = 0;
const priceDiv = document.getElementById("price");
document.addEventListener("click", ({ target }) => {
if (!target.matches("input[type=checkbox]")) {
return;
}
if (clickedCheckboxes.has(target)) {
clickedCheckboxes.delete(target);
sum -= target.value;
} else {
clickedCheckboxes.add(target);
sum += Number(target.value);
}
priceDiv.textContent = `Food Total: $${(sum / 100).toFixed(2)}`;
});
我认为复选框应该有一个简单的布尔值 .checked 为真或假:https://www.w3schools.com/jsref/prop_checkbox_checked.asp
如果 .checked === false
,这可能允许您递减