使用JavaScript级联下拉菜单

时间:2019-07-12 22:19:56

标签: javascript

我正在尝试使用this来实现级联下拉列表。我对Javascript并不是很熟悉,但是我认为我走对了。它应该显示数组值[0, 1, 2, 3],而不是值["Name", "Definition", "Owner"]

var typeObject = {
  StoredProcedures: ["Name", "Definition", "Owner"],
  Tables: ["Name", "Definition", "Owner", "Schema"],
  Views: ["Name", "Definition", "Owner"]
}
window.onload = function() {
    var typeSel = document.getElementById("typeSel"),
      fieldSel = document.getElementById("fieldSel")
    for (var type in typeObject) {
      typeSel.options[typeSel.options.length] = new Option(type, type);
    }
    typeSel.onchange = function() {
      fieldSel.length = 1; // remove all options bar first
      if (this.selectedIndex < 1) return; // done   
      for (var field in typeObject[this.value]) {
        fieldSel.options[fieldSel.options.length] = new Option(field, field);
      }
    }
    typeSel.onchange();

Cascading Picture

1 个答案:

答案 0 :(得分:0)

我对您的脚本进行了修改

var typeObject = {
        StoredProcedures: ["Name", "Definition", "Owner"],
        Tables: ["Name", "Definition", "Owner", "Schema"],
        Views: ["Name", "Definition", "Owner"]
    }
    window.onload = function () {
        var typeSel = document.getElementById("typeSel"),
            fieldSel = document.getElementById("fieldSel")
        for (var type in typeObject) {
            typeSel.options[typeSel.options.length] = new Option(type, type);
        }
        typeSel.onchange = function () {
            fieldSel.length = 1; // remove all options bar first
            if (this.selectedIndex < 1) return; // done  
            var ft = typeObject[this.value];
            for (var field in typeObject[this.value]) {
                fieldSel.options[fieldSel.options.length] = new Option(ft[field], field);
            }
        }
        typeSel.onchange();
    }
<select name="optone" id="typeSel" size="1">
    <option value="" selected="selected">Select type</option>
</select>
<br/>
<br/>
<select name="opttwo" id="fieldSel" size="1">
    <option value="" selected="selected">Select field</option>
</select>