Javascript数组指向具有类似功能的变量名

时间:2015-02-08 05:17:04

标签: javascript arrays function selector

我想用数组缩短此功能

            document.mySchedule.breakfast.onchange = function() {
                var id = document.mySchedule.breakfast.selectedIndex;
                var val = document.mySchedule.breakfast[id].value;
                strUser[0]=val;
            }
            document.mySchedule.lunch.onchange = function() {
                var id = document.mySchedule.lunch.selectedIndex;
                var val = document.mySchedule.lunch[id].value;
                strUser[1]=val;
            }
            document.mySchedule.dinner.onchange = function() {
                var id = document.mySchedule.dinner.selectedIndex;
                var val = document.mySchedule.dinner[id].value;
                strUser[2]=val;
            }

我试试这种方式,但它似乎没有用。

var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
                document.mySchedule.selectData[i].onchange = function() {
                    var id = document.mySchedule.selectData[i].selectedIndex;
                    var val = document.mySchedule.selectData[i][id].value;
                    strUser[i]=val;
                }
            }
顺便说一句,这用来控制选择器。 希望有人能提供帮助。谢谢

1 个答案:

答案 0 :(得分:0)

使用:

var selectData = ["breakfast","lunch","dinner"]
for(i = 0; i < selectData.lenght; i++) {
    var e = document.getElementById(selectData[i]);
    e.onchange = function(){
        strUser[i] = e.value;
    };
}