选择的索引在Javascript中更改

时间:2012-10-19 15:13:18

标签: 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]));
        }

2 个答案:

答案 0 :(得分: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);​

答案 1 :(得分: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>");
        }
    }
});