如何創建:級聯下拉列表

學習如何使用 JavaScript 創建級聯下拉列表。

親自試一試

創建三個下拉列表

在 HTML 表單內創建三個下拉列表。

第二個和第三個下拉列表將顯示不同的選項,具體取決于父下拉列表中選擇的值。

第一步 - 添加 HTML:

<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>
  Chapters: <select name="chapter" id="chapter">
    <option value="" selected="selected">Please select topic first</option>
  </select>
  <br><br>
  <input type="submit" value="Submit">
</form>

第二步 - 添加 JavaScript:

var subjectObject = {
  "Front-end": {
    "HTML": ["Links", "Images", "Tables", "Lists"],
    "CSS": ["Borders", "Margins", "Backgrounds", "Float"],
    "JavaScript": ["Variables", "Operators", "Functions", "Conditions"]
  },
  "Back-end": {
    "PHP": ["Variables", "Strings", "Arrays"],
    "SQL": ["SELECT", "UPDATE", "DELETE"]
  }
}
window.onload = function() {
  var subjectSel = document.getElementById("subject");
  var topicSel = document.getElementById("topic");
  var chapterSel = document.getElementById("chapter");
  for (var x in subjectObject) {
    subjectSel.options[subjectSel.options.length] = new Option(x, x);
  }
  subjectSel.onchange = function() {
    // 清空“章節”和“主題”下拉菜單
    chapterSel.length = 1;
    topicSel.length = 1;
    // 顯示正確值
    for (var y in subjectObject[this.value]) {
      topicSel.options[topicSel.options.length] = new Option(y, y);
    }
  }
  topicSel.onchange = function() {
    // 清空“章節”下拉菜單
    chapterSel.length = 1;
    // 顯示正確值
    var z = subjectObject[subjectSel.value][this.value];
    for (var i = 0; i < z.length; i++) {
      chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
    }
  }
}

親自試一試

相關頁面

教程:CSS 下拉菜單

教程:如何可懸停的下拉菜單