嵌套addEventListener致下拉选框失效的JavaScript表单问题
问题解决:下拉选框失效与价格计算错误修复
嘿,我瞅见你的问题啦!下拉选框最后两个选项失效,选了还是按第一个算,核心原因和几个小问题咱们一个个说:
1. 最致命的错误:条件判断用了赋值运算符
你在if里写的是size.value = "85x200",这是赋值操作,不是判断相等!这行代码会直接把size.value改成85x200,然后这个表达式返回true,所以不管你选哪个尺寸,都会直接进入第一个if分支,后面的else if和else根本不会执行。
修复方法:把所有条件里的=换成严格相等的===:
if (size.value === "85x200") { ... } else if (size.value === "100x200") { ... } else { ... }
2. 事件监听嵌套导致重复触发
你把尺寸的change事件监听放在了数量的input事件里面,这意味着每次用户输入数量,都会给下拉框多绑一次change事件,次数多了会触发多次计算,搞不好还会出奇怪的bug。
修复方法:把两个事件监听分开,单独写一个计算函数,两个事件都调用它:
document.addEventListener("DOMContentLoaded", function() { "use strict"; let amount = document.getElementById('amount'); let size = document.getElementById('size'); let spanPrice = document.getElementById('output'); // 单独拎出计算逻辑 function calculateTotal() { // 先把价格转成可用的数字:去掉" zł",把逗号换成小数点 const priceElements = document.querySelectorAll("td.price"); const prices = [...priceElements].map(el => { const priceText = el.textContent.trim().replace(' zł', '').replace(',', '.'); return parseFloat(priceText); }); // 处理数量:避免0的情况,因为input的min是1 const quantity = parseInt(amount.value) || 1; let unitPrice = 0; // 正确判断尺寸 if (size.value === "85x200") { if (quantity <= 10) unitPrice = prices[0]; else if (quantity <= 30) unitPrice = prices[1]; else if (quantity <= 50) unitPrice = prices[2]; else unitPrice = prices[3]; } else if (size.value === "100x200") { if (quantity <= 10) unitPrice = prices[4]; else if (quantity <= 30) unitPrice = prices[5]; else if (quantity <= 50) unitPrice = prices[6]; else unitPrice = prices[7]; } else if (size.value === "120x200") { if (quantity <= 10) unitPrice = prices[8]; else if (quantity <= 30) unitPrice = prices[9]; else if (quantity <= 50) unitPrice = prices[10]; else unitPrice = prices[11]; } // 计算总价,转回带逗号的波兰货币格式 return (quantity * unitPrice).toFixed(2).replace('.', ','); } // 统一的更新函数 function updatePrice() { const total = calculateTotal(); spanPrice.textContent = total; } // 给两个控件绑定事件 amount.addEventListener('input', updatePrice); size.addEventListener('change', updatePrice); // 页面加载时就更新一次(如果有默认值的话) updatePrice(); });
3. 价格字符串处理的小坑
原来的slice(0, -6)虽然能去掉" zł",但如果价格格式变了就会出错,而且带逗号的字符串直接相乘会得到错误结果(比如"285,00" * 2会变成57000而不是570),所以我们先把价格转成浮点数计算,最后再转回带逗号的格式,符合波兰货币的显示习惯。
4. 可选的HTML优化
给下拉选框的第一个选项加上value="",这样更容易判断用户有没有选有效尺寸:
<select name="size" id="size"> <option value="">Kliknij, aby wybrać</option> <option value="85x200">85cm x 200 cm</option> <option value="100x200">100cm x 200 cm</option> <option value="120x200">120cm x 200 cm</option> </select>
这样改完之后,三个尺寸选项都能正常触发对应的价格计算,而且结果也会准确显示啦!
内容的提问来源于stack exchange,提问作者Wiktoria Tomzik
相关产品推荐
相关产品推荐

