0

我想根据先前选择的选项的值填充选择选项。

            <label for="state" class="block">State:*</label>
            <select name="state" id="state" tabindex="1">
                <option value="Arizona">Arizona</option>
                <option value="Arkansas">Arkansas</option>
                <option value="Colorado">Colorado</option>
            </select>

            <label for="location" class="block">Preferred Location:*</label>
            <select name="location" id="location" tabindex="2">
                <option value=""></option>
            </select>

那是我的html。现在我有我的js,它可以工作,但我想知道是否有一种方法。

        var State = $('#state').val();
        var Location = $('#location');



        setOptions(State);

        function setOptions(chosen){

        var Location=document.myform.location;
        Location.options.length=0;

        var Arizona = {
        0 : 'Select Location',
        3 : 'Phoenix (Chandler)',
        4 : 'Scottsdale',
        5 : 'Tuscon'
        };

        var Arkansas = {
        2 : 'Little Rock'
        };          

        var Colorado = {
        6 : 'Colorado Springs'
        };




        if(chosen=="Arizona"){              
        var myobject = Arizona;
        }

        if(chosen=="Arkansas"){
        var myobject = Arkansas;
        }

        if(chosen=="Colorado"){         
        var myobject = Colorado;
        }

        for(index in myobject) {
                Location.options[Location.options.length]=new Option(myobject[index], index);
        }

有没有办法根据另一个选择框告诉它使用哪个对象?

谢谢!

4

1 回答 1

0

使用嵌套对象:

var locations = {
    Arizona: {
        0 : 'Select Location',
        3 : 'Phoenix (Chandler)',
        4 : 'Scottsdale',
        5 : 'Tuscon'
    },
    Arkansas: {
        2 : 'Little Rock'
    },
    Colorado: {
        6 : 'Colorado Springs'
    }
};

var myobject = locations[chosen];
for(index in myobject) {
    Location.options.push(new Option(myobject[index], index));
}
于 2013-04-08T18:28:55.820 回答