如何使用JavaScript在<select>标签<option>选中后弹出Map()存储的值
原代码错误点
- Map没有
length属性,你写的循环条件i<avgGrade.length判断不成立,循环完全不会执行 avgGrade.keys()返回的是整个Map的键迭代器对象,不是单个学生姓名,直接赋值给option.innerHTML会显示[object Map Iterator]而非学生名studentGrades函数中使用的Select、selectedIndex、i都是未声明的变量,无法正确获取选中项信息- Map不能用数组下标
[i]的方式取值,必须调用get()方法传入键来获取对应值
修正后的完整代码
HTML部分
<!-- 下拉菜单DOM结构 --> <select id="dropdown" onchange="studentGrades()"></select>
JavaScript部分
// 已初始化的成绩Map const avgGrade = new Map(); avgGrade.set('Kyle', '82%'); avgGrade.set('Sarah', '50%'); avgGrade.set('Skye', '96%'); avgGrade.set('Taylor', '75%'); avgGrade.set('Bantu', '98%'); // 生成下拉选项 const dropdown = document.querySelector('#dropdown'); // 遍历Map的所有学生姓名生成option for (const studentName of avgGrade.keys()) { const option = document.createElement('option'); option.value = studentName; option.innerHTML = studentName; dropdown.appendChild(option); } // 选中学生后触发弹窗 function studentGrades() { const selectedStudent = dropdown.value; const grade = avgGrade.get(selectedStudent); alert(`${selectedStudent}的平均成绩是${grade}`); }
内容的提问来源于stack exchange,提问作者ZuriS
相关产品推荐
相关产品推荐

