javascript - 在 Javascript 中更改了选定的索引

标签 javascript jquery arrays drop-down-menu

我有一个带有值的下拉列表 Grade

["a", "b", "c"]

在下拉列表的选择更改时,应加载 Student 下拉列表的值。

when "a" is selected, Dropdown students should populate ["Anna", "Hannah"]
When "b" is selected, Dropdown students should populate ["Billy", "Cathy"]
When "c" is selected, Dropdown students should populate ["Albert", "Deepti"]

我们能否将所有成绩和学生保存在单个数组中(在 js 文件中)?如果是,我如何才能仅加载数组中在 javascript 中更改的选定索引上的那些值?

要添加到描述中,我的代码是 HTML 格式,所以我的控件是:

 <select id="grade" name="grade"></select>
 <select id="student" name="student"></select>

修改:

    var grades_rank;
    var grades_student;
    var grades = {     "very good": ["Anna", "Hannah"],     "good":
 ["Billy", "Cathy"],     "above average": ["Albert", "Deepti"] }  ;

加载下拉列表:

for (var _i = 0; _i < grades.length; _i++) {
            jQ('#Stu_Grades').append(jQ("<option></option>").attr("value", _i).text(grades[_i][grades_rank]));
        }

最佳答案

使用对象:

var grades = {
    a: ["Anna", "Hannah"],
    b: ["Billy", "Cathy"],
    c: ["Albert", "Deepti"]
}

当下拉值发生变化时,使用其新值来查找您要使用的名称:

grades[a]; // ["Anna", "Hannah"]
grades[b]; // ["Billy", "Cathy"]

当一切都说完了,它可能看起来像下面这样:

// Lookup chart for grades and students
var grades = {
    a: ["Anna", "Hannah"],
    b: ["Billy", "Cathy"],
    c: ["Albert", "Deepti"]
}

// Reference our dropdown lists
var grade = document.getElementById("grade");
var student = document.getElementById("student");

// Add an event handler to the 'change' event on our grades
grade.addEventListener("change", function(){
    // A few variables we'll use
    var option, g, c, i;
    // Clear student list
    while ( c = student.firstChild ) student.removeChild( c );
    // If the new value is a grade in our lookup
    if ( g = grades[ this.value ] ) {
        // Populate student list
        for ( i = 0; i < g.length; i++ ) {
            option = document.createElement("option");
            option.text = g[i];
            student.appendChild(option);
        }
    }
}, false);​

关于javascript - 在 Javascript 中更改了选定的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977265/

相关文章:

javascript - 点击事件在 dcmads 上不起作用

javascript - 如何在javascript中委托(delegate)它?

javascript - 管理事件状态

javascript - event.target 在 Firefox 中未定义,在 IE 中出现小错误

c++ - 使用数组填充对称矩阵

javascript - DYMO LabelWriter 获取打印回调

javascript - 隐藏在 li 标签中的 div

jquery - html如何引用input标签中的文件

c++ - SWIG 如何使用 Lua 表从 Lua 中的 c 结构访问字节数组以进行操作

ruby - 如何在 Ruby 中声明一个二维数组