使用变量对象名访问嵌套对象的键

时间:2014-01-14 03:56:18

标签: javascript jquery arrays object drop-down-menu

不是100%肯定我的问题的标题准确地说明了我的问题,我提前道歉。如果我的术语在这里,请纠正我。

基本上,我有一个选择框。当用户进行选择时,我想创建一个新的选择框,使用存储在对象中的值设置其选项:

jsFiddle 显示我的尝试

我的代码:

HTML:

<SELECT id="mainIssueType"  style="color:#888"size=0>
    <OPTION style="color:#888" selected> Issue Type </option>
    <OPTION style="color:#888" value="Hotel"> Hotel </option>
    <OPTION style="color:#888" value="Flights"> Flights </option>
</SELECT>

脚本:

var tree = {
    "Hotel": [{val: "Htl1", text: 'Cancel'},
        {val: "Htl2", text: 'Modify'},
        {val: "Htl3", text: 'Research'},
        {val: "Htl4", text: 'Complaint'}],
    "Flights": [{val: "Flt1", text: 'Void'},
        {val: "Flt1", text: 'Cancel'},
        {val: "Flt1", text: 'Change Flight'},
        {val: "Flt1", text: 'Schedule Change'},
        {val: "Flt1", text: 'Name Change'}, ]
};



$(function() {

    $('#mainIssueType').change(function() {
        //get current selected option
        var selectVal = $('#mainIssueType :selected').val();
        //create a new select box and add to body
        var sel = $('<select>').appendTo('body');
        //give the new element an id matching 
        //the selected value from the previous element
        sel.attr('id', selectVal);
        //set the select box's options using the values 
        //from the "selectVal" object within the "tree" object
        $(tree.selectVal).each(function() {
            //tree.selectVal seems to be the problem
            sel.append($("<option>").attr('value', this.val).text(this.text));
        });
    });
});

tree.selectVal中的$(tree.selectVal).each似乎是问题所在。我想这与直接说tree.Hotel不一样,因为我可以使用tree.Hotel显示here

如何访问名称与我的tree变量匹配的selectVal中的对象?

1 个答案:

答案 0 :(得分:1)

使用$(tree[selectVal])代替$(tree.selectVal)

$(function(){

   $('#mainIssueType').change(function() {
        //get current selected option
        var selectVal = $('#mainIssueType :selected').val(); 
        //create a new select box and add to body
        var sel = $('<select>').appendTo('body');
        //give the new element an id matching 
        //the selected value from the previous element
        sel.attr('id',selectVal);
        //set the select box's options using the values 
        //from the "selectVal" object within the "tree" object
        $(tree[selectVal]).each(function() {
            //_____^_____________________
            //tree.selectVal seems to be the problem
            sel.append($("<option>").attr('value',this.val).text(this.text));
        }); 
    });

});

FIDDLE DEMO

相关问题