如何根据下拉选择框选项修改HTML表格中的服务价格?
解决车型选择后服务价格动态更新的问题
原代码存在的问题
- 价格更新逻辑仅在页面初始化时执行一次,未监听车型下拉框的
change事件,无法响应车型选择变化 - 条件判断中使用赋值运算符
=而非比较运算符===,导致逻辑判断失效 - 未正确获取当前选中的车型值,
cars变量未定义 - 多个独立的
if语句会互相覆盖结果,逻辑执行顺序有问题 - 车型下拉框的option标签存在语法错误(多余的双引号)
修正后的代码
HTML部分(保持原有结构)
<p>Factory <br> <select id="brandselect"> <option value="Toyota"> Toyota</option> <option value="Nissan"> Nissan</option> <option value="Volkswagen"> Volkswagen</option> </select> </p> <p>Model <br> <select id="carselect"> </select> </p> <table> <tr> <th>Choice </th> <th>Service </th> <th>Price $ </th> </tr> <tr> <td><input type="checkbox"></td> <td>Washing</td> <td> <p id="washing"></p> </td> </tr> <tr> <td><input type="checkbox"></td> <td>Polishing</td> <td> <p id="polishing"></p> </td> </tr> </table>
JavaScript部分
const options = { 'Toyota': { cars: ['Camry', 'Corolla', 'Yaris Sedan'] }, 'Nissan': { cars: ['bluebird', 'Murano', 'Tiida'] }, 'Volkswagen': { cars: ['MarkX', 'Avensis'] } }; // 统一管理各车型的服务价格,方便后续扩展 const carPrices = { 'Camry': { washing: 20, polishing: 20 }, 'Corolla': { washing: 30, polishing: 30 }, 'Yaris Sedan': { washing: 15, polishing: 15 }, 'bluebird': { washing: 25, polishing: 25 }, 'Murano': { washing: 35, polishing: 35 }, 'Tiida': { washing: 20, polishing: 20 }, 'MarkX': { washing: 30, polishing: 30 }, 'Avensis': { washing: 28, polishing: 28 } }; function updateCarByBrand() { const carselect = document.getElementById('carselect'); carselect.innerHTML = ""; options[brandselect.value].cars.forEach(e => { // 修复option标签的语法错误 carselect.innerHTML += `<option value="${e}">${e}</option>`; }); // 品牌切换后自动更新当前车型价格 updateServicePrices(); } function updateServicePrices() { const carselect = document.getElementById('carselect'); const selectedCar = carselect.value; const washingEl = document.getElementById('washing'); const polishingEl = document.getElementById('polishing'); // 匹配选中车型的价格,无匹配时默认设为0 const prices = carPrices[selectedCar] || { washing: 0, polishing: 0 }; washingEl.innerHTML = prices.washing; polishingEl.innerHTML = prices.polishing; } const brandselect = document.getElementById('brandselect'); const carselect = document.getElementById('carselect'); // 绑定事件监听 brandselect.addEventListener('change', updateCarByBrand); carselect.addEventListener('change', updateServicePrices); // 初始化页面时加载车型和对应价格 updateCarByBrand(); updateServicePrices();
关键改进点
- 新增
carPrices对象统一管理价格,后续添加新车型只需补充数据,无需修改逻辑 - 拆分出
updateServicePrices函数专门处理价格更新,代码职责更清晰 - 给车型下拉框添加
change事件监听,确保选中车型变化时自动更新价格 - 修复option标签的语法错误,避免潜在的选择异常
- 品牌切换后自动触发价格更新,保证初始状态的正确性
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

