簡體   English   中英

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

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

我在 JavaScript 訓練營的第二周,需要用地圖項填充下拉列表。 下拉菜單應顯示學生姓名,當它被選中時,該值應在警報中彈出。 我沒有壓力的警報部分,但現在我的下拉列表沒有填充。

我之前使用過類似的代碼來填充下拉 iwth 數組項,但由於某種原因,我無法弄清楚這里出了什么問題。

任何幫助都會很棒。

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

/* 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.
    }
}

@trincot 提供的答案

Map#set 是一個函數,而不是一個 setter,所以你不應該使用 =。 使用 studentGrd.set("Chrisna", 86) 進行修復。 投票以錯字結束。 – 昨天特里科特

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM