为什么输入值显示在控制台中,但不显示在下拉框中?

我构建了一个接受用户输入的基本报告程序,将此输入添加到一系列添加到下拉列表的段落中。然后将选择添加到数组中并打印在最终报告中。


这是该程序的 JFiddle。正如您将看到的,您的输入会打印在控制台中,但不会被拉到下拉列表中。你能帮我弄清楚为什么吗?


function populateSelects(dropDownConfig) {

    console.log(`I can get the student name here, but not in the dropdown box. Your name is ${studentName}.`);


for (let di = 0; di < dropDownConfig.length; di++) {

  for (let i = 0; i < dropDownConfig[di].categoryOptions.length; i++) {

    let opt = dropDownConfig[di].categoryOptions[i];


    let el = document.createElement("option");

    el.text = opt;

    el.value = opt;


    document.getElementById(dropDownConfig[di].id).add(el);

  }

}

}

该函数似乎可以正常工作,但不适用于 studentName/inputStudentName 的值。


谢谢!


慕尼黑5688855
浏览 145回答 1
1回答

HUWWW

恕我直言,我已经稍微更改了您的代码以使其更短且更具可读性。我所做的主要更改是使用占位符文本而不是变量,并在创建选项时将其替换为 studentName。let options= {&nbsp; progress: ['%NAME% has made excellent progress', '%NAME% has made good progress', '%NAME% has made poor progress'],&nbsp; behaviour: ['%NAME% has excellent behaviour', '%NAME% has good behaviour', '%NAME% has poor behaviour'],&nbsp; attendance: ['%NAME% has excellent attendance', '%NAME% has good attendance', '%NAME% has poor attendance'],&nbsp; punctuality: ['%NAME% has excellent punctuality', '%NAME% has good punctuality', '%NAME% has poor punctuality'],&nbsp; improvements: ['%NAME% should carry on as they have', '%NAME% could make some improvements', '%NAME% must improve']}let dropDownConfig = ["progress", "behaviour", "attendance", "punctuality", "improvements"];function populateSelects(dropDownConfig) {&nbsp; dropDownConfig.forEach(config => {&nbsp; &nbsp; let select = document.querySelector(`#${config}Dropdown`);&nbsp; &nbsp; options[config].forEach(text => {&nbsp; &nbsp; &nbsp; &nbsp; let option = document.createElement("OPTION");&nbsp; &nbsp; &nbsp; &nbsp; text = text.replace("%NAME%", studentName);&nbsp; &nbsp; &nbsp; &nbsp; option.text = text;&nbsp; &nbsp; &nbsp; &nbsp; option.value = text;&nbsp; &nbsp; &nbsp; &nbsp; select.appendChild(option);&nbsp; &nbsp; })&nbsp; })}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript