
本文介绍如何通过监听品牌与车型下拉框的变更事件,动态更新表格中“清洗”和“抛光”服务对应的价格,使用结构化数据与事件驱动逻辑实现响应式价格展示。
本文介绍如何通过监听品牌与车型下拉框的变更事件,动态更新表格中“清洗”和“抛光”服务对应的价格,使用结构化数据与事件驱动逻辑实现响应式价格展示。
在 Web 表单中,常需根据用户选择(如汽车品牌 → 车型)级联更新关联数据(如服务价格)。原始代码存在多个关键问题:if (cars = 'Camry') 使用了赋值运算符 = 而非比较运算符 ===;缺少对车型选择变化的监听;价格逻辑未封装且重复冗余;未处理未定义车型的默认值。
以下是优化后的完整实现方案:
文章转信息图。将文章/笔记转化为手机可读的 HTML 信息图,自动匹配视觉风格。触发场景:文章转图、笔记转图、信息图、转小红书图、做张图、可视化这篇文章、文生图。
✅ 核心思路
- 双级联动:先监听品牌 <select> 变更,动态生成对应车型选项;再监听车型 <select> 变更,实时更新价格。
- 数据驱动:将价格信息独立维护在 prices 对象中,键为车型名,值为各服务价格对象,便于扩展与维护。
- 健壮性保障:使用逻辑或 || 提供默认价格({ washing: 0, polishing: 0 }),避免 undefined 导致脚本错误。
✅ 完整可运行代码
<p>工厂品牌<br>
<select id="brandselect">
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
<option value="Volkswagen">Volkswagen</option>
</select>
</p>
<p>车型<br>
<select id="carselect"></select>
</p>
<table border="1" style="border-collapse: collapse; margin-top: 16px;">
<tr>
<th>选择</th>
<th>服务</th>
<th>价格($)</th>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>清洗(Washing)</td>
<td><p id="washing">0</p></td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>抛光(Polishing)</td>
<td><p id="polishing">0</p></td>
</tr>
</table>
<script>
const options = {
'Toyota': { cars: ['Camry', 'Corolla', 'Yaris Sedan'] },
'Nissan': { cars: ['bluebird', 'Murano', 'Tiida'] },
'Volkswagen': { cars: ['MarkX', 'Avensis'] }
};
const prices = {
"Camry": { washing: 20, polishing: 20 },
"Corolla": { washing: 30, polishing: 30 }
// 其他车型将自动使用默认价格 { washing: 0, polishing: 0 }
};
const brandselect = document.getElementById('brandselect');
const carselect = document.getElementById('carselect');
function updateCarByBrand() {
carselect.innerHTML = '';
const cars = options[brandselect.value]?.cars || [];
cars.forEach(car => {
const option = document.createElement('option');
option.value = car;
option.textContent = car;
carselect.appendChild(option);
});
}
function updatePriceByModel() {
const selectedCar = carselect.value;
const price = prices[selectedCar] || { washing: 0, polishing: 0 };
document.getElementById('washing').textContent = price.washing;
document.getElementById('polishing').textContent = price.polishing;
}
// 初始化并绑定事件
updateCarByBrand();
brandselect.addEventListener('change', updateCarByBrand);
carselect.addEventListener('change', updatePriceByModel);
updatePriceByModel(); // 初始化价格显示
</script>⚠️ 注意事项
- DOM 元素获取时机:确保 <script> 放在 HTML 底部,或使用 DOMContentLoaded 包裹,防止元素未加载导致 getElementById 返回 null。
- 安全性增强:生产环境中建议用 textContent 替代 innerHTML 更新 <p> 内容,避免 XSS 风险(示例已采用)。
- 可扩展建议:如需支持更多服务(如打蜡、内饰清洁),只需在 prices 对象中扩展字段,并在表格中新增对应行即可。
- 用户体验优化:可添加 disabled 属性控制车型下拉框初始禁用状态,待品牌选择后才启用。
通过这种解耦设计(数据分离 + 事件驱动),代码更易维护、测试与扩展,是前端动态表单交互的典型实践模式。


















