使用Map.set创建并填充Select元素,选中时弹出对应值的JS问题求助
问题:用Map填充下拉框,选中选项弹出对应分数
我是前端新手,想做一个简单的select元素,用Map来填充选项;选中下拉框里的名字时,弹出alert显示对应的分数。目前写了一些代码,但不确定哪里有问题,求反馈和建议。
我的代码如下:
原始JS代码
const studentMap = new Map(); studentMap.set("Dave", 89); studentMap.set("Angela", 88); studentMap.set("Luke", 97); studentMap.set("Holly", 95); studentMap.set("Ziggy", 89); function dropDownGrades() { let select = document.createElement("SELECT"); select.setAttribute("id", "mySelect"); dropDownGradeBox.appendChild(select); for (let i = 0; i < studentMap.length; i++) { let names = studentMap.set(key); let newOption = document.createElement("option"); newOption.setAttribute("id", "nameOptions"); let textNode = document.createTextNode(names); newOption.appendChild(textNode); select.appendChild(newOption); } }
原始HTML代码
<head> <script type="text/Javascript" src="task2.js"></script> </head> <body onload = "dropDownGrades()"> <h1> Task 11 - Name and Grades</h1> <p> Below is the dropdown list of names and, when clicked on, it should hopefully display an alert box with the respective grade </p> <div id="dropDownGradeBox" onchange="studentGrade()"></div> </body>
问题分析与修正建议
1. Map遍历错误
- Map没有
length属性,获取元素数量要用studentMap.size - 遍历Map不能用普通for循环,推荐用
for...of遍历键值对,或者studentMap.keys()遍历所有名字 - 你写的
studentMap.set(key)是错误的,set是用来添加键值对的,不是获取键,应该直接遍历Map的键
2. 事件绑定错误
onchange事件绑定在<div>上无效,应该绑定到<select>元素上- 你定义的
studentGrade函数不存在,需要补充实现
3. 其他细节问题
- 所有option的id都是
nameOptions,id必须唯一,这里没必要给option加id - 创建option可以用更简洁的
new Option(text, value)语法,同时把名字设为option的value,方便后续获取
修正后的代码
修正后的JS代码
const studentMap = new Map(); studentMap.set("Dave", 89); studentMap.set("Angela", 88); studentMap.set("Luke", 97); studentMap.set("Holly", 95); studentMap.set("Ziggy", 89); function dropDownGrades() { const select = document.createElement("select"); select.setAttribute("id", "mySelect"); // 把onchange绑定到select上 select.addEventListener('change', studentGrade); dropDownGradeBox.appendChild(select); // 遍历Map的所有键(名字) for (const name of studentMap.keys()) { // 简洁创建option,文本和value都设为名字 const option = new Option(name, name); select.appendChild(option); } } // 实现studentGrade函数 function studentGrade() { const select = document.getElementById('mySelect'); const selectedName = select.value; const grade = studentMap.get(selectedName); alert(`${selectedName}的分数是:${grade}`); }
修正后的HTML代码
<head> <title>学生分数查询</title> </head> <body onload="dropDownGrades()"> <h1> Task 11 - Name and Grades</h1> <p> 以下是学生名字下拉框,选中后会弹出对应的分数</p> <div id="dropDownGradeBox"></div> <!-- 把脚本放在body末尾,确保DOM加载完成 --> <script type="text/javascript" src="task2.js"></script> </body>
内容的提问来源于stack exchange,提问作者L-Stoney
相关产品推荐
相关产品推荐

