1

我有一个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]));
        }
4

2 回答 2

1

如果您真的想要一个数组,则可以将它们全部保存在一组对象中

var studentsByGrade = [ 
    { "grade": "a", "name": "Anna" }, 
    { "grade": "a", "name": "Hannah" }, 
    { "grade": "b", "name": "Billy" }, 
    { "grade": "b", "name": "Cathy" }, 
    { "grade": "c", "name": "Albert" }, 
    { "grade": "c", "name": "Deepti" }
];

使用它来填充#grade 下拉列表:

for (var i=0;i<studentsByGrade.length;i++) {
    if ($("#grade option[value='+"studentsByGrade[i].grade"+']").length === 0) {
        $("#grade").append("<option value='"+studentsByGrade[i].grade+'>"+studentsByGrade[i].grade+"</option>");
    }
}

并将其作为更改处理程序放在#grade 下拉列表中:

$("#grade").on('change', function() {
    var grade = this.value;        
    students.innerHTML = "";
    for (var i=0;i<studentsByGrade.length;i++) {
        if (studentsByGrade[i].grade == grade) {
            $("#student").append("<option value='"+studentsByGrade[i].name+'>"+studentsByGrade[i].name+"</option>");
        }
    }
});
于 2012-10-19T15:43:07.740 回答
1

使用一个对象:

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);​
于 2012-10-19T15:17:21.417 回答