[英]How to alert map() values after an <option> of a <select> tag has been selected using Javascript?
I was tasked to use a map to store the names of 5 students with their corresponding average grade.我的任务是使用地图来存储 5 名学生的姓名及其相应的平均成绩。 I have initialised this map with fictitious hardcoded names and grades as follows:
我已使用虚构的硬编码名称和等级初始化此地图,如下所示:
const avgGrade = new Map();
avgGrade.set('Kyle', '82%');
avgGrade.set('Sarah', '50%');
avgGrade.set('Skye', '96%');
avgGrade.set('Taylor', '75%');
avgGrade.set('Bantu', '98%');
My goal is to write the JavaScript to display the name of each student in a drop-down menu.我的目标是编写 JavaScript 以在下拉菜单中显示每个学生的姓名。 When the student's name is selected from the drop-down menu, the student's grade should be displayed using an alert.
当从下拉菜单中选择学生的姓名时,应使用警报显示学生的成绩。 These are the hints I was given (Hint: Remember that you can use the value and innerHTML attributes of an element.)
这些是我得到的提示(提示:请记住,您可以使用元素的 value 和 innerHTML 属性。)
I tried doing this, but there is something I'm not getting right.我试过这样做,但有些事情我没有做对。 can someone please tell me where I'm going wrong.
有人可以告诉我我哪里出错了。 Here's my code:
这是我的代码:
//dropdown menu using a for loop
let dropdown = document.querySelector('#dropdown');
for (i=0; i<avgGrade.length; i++){
let option = document.createElement('option');
option.innerHTML = avgGrade.keys();
dropdown.appendChild(option);
}
//also,I to just alert like this:
function studentGrades()//called the function in select tag on the DOM using the onchange event
{
alert( Select.options[selectedIndex].value + ' average grade is ' + avgGrade.values[i]);
}
You will have to make sure you are iterating Map
correctly.您必须确保正确地迭代
Map
。 You can use forEach()
for that.您可以为此使用
forEach()
。 To insert your options
please give both text
and value
.要插入您的
options
请同时提供text
和value
。
Variables like Select
, i
, selectedIndex
are not defined in your code.您的代码中未定义
Select
、 i
、 selectedIndex
等变量。
To get the values from Map
, please use standard Map methods like get()
.要从
Map
获取值,请使用标准 Map 方法,例如get()
。
const avgGrade = new Map(); avgGrade.set('Kyle', '82%'); avgGrade.set('Sarah', '50%'); avgGrade.set('Skye', '96%'); avgGrade.set('Taylor', '75%'); avgGrade.set('Bantu', '98%'); let dropdown = document.querySelector('#dropdown'); avgGrade.forEach((val, key) => { let option = document.createElement('option'); option.text = key; option.value = key; dropdown.appendChild(option); }); //also,I to just alert like this: function studentGrades(select) { //called the function in select tag on the DOM using the onchange event alert(select.value + ' average grade is ' + avgGrade.get(select.value)); }
<select id="dropdown" onchange="studentGrades(this)"> </select>
I took the liberty of passing this
as an argument on the onChange.我冒昧地
this
作为 onChange 的论据传递。 You might be doing it some other way.你可能正在以其他方式做这件事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.