简体   繁体   English

在原生 JavaScript 中使用映射键和值填充下拉列表

[英]Populating Dropdown with Map Keys and Values in vanilla JavaScript

I'm in my second week of a JavaScript bootcamp and need to populate the dropdown with map items.我在 JavaScript 训练营的第二周,需要用地图项填充下拉列表。 The dropdown should display the student name and when it is selected, the value should pop up in an alert.下拉菜单应显示学生姓名,当它被选中时,该值应在警报中弹出。 The alert part I am not stressed about but right now my drowpdown is not populating.我没有压力的警报部分,但现在我的下拉列表没有填充。

I've used similar code to populate a dropdown iwth array items before but for some reason I can't figure out whats's wrong here.我之前使用过类似的代码来填充下拉 iwth 数组项,但由于某种原因,我无法弄清楚这里出了什么问题。

Any assistance will be great.任何帮助都会很棒。

HTML HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="./task2.js"></script>
    <title>Task 2</title>    
</head>
<body>
    <div>
        <select id="studentGrades"></select>
    </div>
</body>
</html>

JS JS

/* Here we will write a function that populates a dropwdown with the names of students. When the name of the student is selected an alert will display their grade on the screen. */

// Creating a new map.
let studentGrd = new Map();

// Populating the map with key value pairs.
studentGrd.set = ("Chrisna", 86);
studentGrd.set = ("Llwellyn", 72);
studentGrd.set = ("Jono", 81);
studentGrd.set = ("Nomafa", 93);
studentGrd.set = ("Mygan", 89);

/* This function will run when the browser window loads */
window.onload =  function() {    

// Create a variable for the select element.
var studentGrades = document.getElementById("studentGrades");

    // Iterates throught the map and generates an option for each key value pair.
    for (let [key, value] of studentGrd) {
        let grdOption = document.createElement("OPTION"); // Creates the dropdown options.
            grdOption.innerHTML = key; // Set what will be displayed in each dropdown option.
            grdOption.value = value; // Sets the value for each dropdown.
            studentGrades.appendChild(grdOption); // Adds the option to the dropdown selection.
    }
}

Answer as provided by @trincot @trincot 提供的答案

Map#set is a function, not a setter, so you should not use =. Map#set 是一个函数,而不是一个 setter,所以你不应该使用 =。 Fix with studentGrd.set("Chrisna", 86).使用 studentGrd.set("Chrisna", 86) 进行修复。 Voting to close as typo.投票以错字结束。 – trincot yesterday – 昨天特里科特

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM