不是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
中的对象?
答案 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));
});
});
});