使用HTML select搭配JavaScript无法实时更新页面字段如何解决?
问题根因
现有JavaScript逻辑仅在页面首次加载时执行一次,没有为下拉菜单绑定change事件监听器,切换选项时不会重新触发字段更新逻辑,因此无法实现实时变更。
修正后代码
无需修改HTML代码,仅需调整JavaScript逻辑如下:
const txt1 = document.querySelector('.txt1'); const txt2 = document.querySelector('.txt2'); const editionsSelect = document.getElementById("editions"); // 封装字段更新逻辑 function updateField() { const selectedValue = editionsSelect.value; if (selectedValue === "Ultimate") { txt1.innerText = 'Ultimate' txt2.innerText = '$99.99' } else if (selectedValue === "Standard") { txt1.innerText = 'Standard' txt2.innerText = '$59.99' } else if (selectedValue === "Legacy") { txt1.innerText = 'Legacy' txt2.innerText = '$79.99' } } // 页面加载完成后初始化字段 updateField() // 绑定下拉切换事件,切换选项时自动更新字段 editionsSelect.addEventListener('change', updateField)
优化建议(可选)
可以用对象映射代替多层if else判断,后续新增选项时只需修改映射配置即可,代码更易维护:
const txt1 = document.querySelector('.txt1'); const txt2 = document.querySelector('.txt2'); const editionsSelect = document.getElementById("editions"); // 版本和价格映射表 const editionMap = { Ultimate: { name: 'Ultimate', price: '$99.99' }, Standard: { name: 'Standard', price: '$59.99' }, Legacy: { name: 'Legacy', price: '$79.99' } } function updateField() { const current = editionMap[editionsSelect.value] txt1.innerText = current.name txt2.innerText = current.price } updateField() editionsSelect.addEventListener('change', updateField)
内容的提问来源于stack exchange,提问作者Oluwagbemiga David
相关产品推荐
相关产品推荐

