用HTML和JavaScript实现二级联动下拉菜单:解决显示索引问题
二级联动下拉菜单显示数组索引的问题修复
问题出在JavaScript脚本中,有两个关键错误:
- 使用
for...in遍历数组时,获取到的是数组的索引(0、1、2这类数值),而非数组里的实际内容(HTML、CSS等) - 代码残留了三级联动的
chapterSel变量,该变量未定义,会触发控制台报错,干扰逻辑执行
以下是修正后的完整代码:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script> var subjectObject = { "Front-end": [ "HTML", "CSS", "JavaScript" ], "Back-end": [ "PHP", "SQL" ] } window.onload = function() { var subjectSel = document.getElementById("subject"); var topicSel = document.getElementById("topic"); for (var x in subjectObject) { subjectSel.options[subjectSel.options.length] = new Option(x, x); } subjectSel.onchange = function() { // 清空Topics下拉菜单 topicSel.length = 1; // 遍历选中分类对应的数组元素 const topics = subjectObject[this.value]; topics.forEach(topic => { topicSel.options[topicSel.options.length] = new Option(topic, topic); }); } } </script> </head> <body> <h1>Cascading Dropdown Example</h1> <form name="form1" id="form1" action="/action_page.php"> Subjects: <select name="subject" id="subject"> <option value="" selected="selected">Select subject</option> </select> <br><br> Topics: <select name="topic" id="topic"> <option value="" selected="selected">Please select subject first</option> </select> <br><br> </form> </body> </html>
也可以用普通for循环替代forEach,效果一致:
// 替换forEach部分 for (let i = 0; i < topics.length; i++) { topicSel.options[topicSel.options.length] = new Option(topics[i], topics[i]); }
内容的提问来源于stack exchange,提问作者harshith swamy
相关产品推荐
相关产品推荐

