我有一个Javascript对象,它包含嵌套对象,但我似乎无法访问嵌套对象 - 对象的格式如下:
Object
0: Object
colour: Object
colour: value
element: value
kelvin: Object
colour: value
element: value
status: Object
state: value
element: value
1: Object
colour: Object
colour: value
element: value
kelvin: Object
status: Object
当我对父对象进行字符串化时,它不包含嵌套对象:
{"0":{},"1":{},"2":{},"3":{},"4":{},"5":{}}
任何人都可以帮我确定我做错了吗?
提前致谢!
以下是我遇到问题的代码:
function updateStatus()
{
var triggers = {};
counter = 0;
$.when(
$("form[type='light_status']").each(function(f){
var options = {};
form = $(this);
selector = form.attr('selector');
id = form.attr('id');
$.ajax({
url: '/status/' + selector + '/' + id,
method: 'GET',
success: function(data) {
var data = $(data)[0];
var switchInput = '#'+data.selector+'-'+data.id;
if(data.status == 'on')
{
options.status = {element: switchInput, state: true};
}
else
{
options.status = {element: switchInput, state: false};
}
options.colour = {element: '#'+data.id+'-colourpicker', colour: data.colour};
options.kelvin = {element: '#'+data.id+'-kelvinpicker', colour: data.colour};
}
});
triggers[counter] = options;
counter++;
})
).done( function() {
console.log(triggers); //can see all nested objects
console.log(triggers[0].colour); //returns null
console.log('triggers:' + JSON.stringify(triggers)); // can only see parent object
});
}
答案 0 :(得分:0)
您可以收集数组中的所有延迟,然后将其传递给$.when()
。
以下是您的回答
function updateStatus() {
var triggers = {};
counter = 0, deferArr = [];
$("form[type='light_status']").each(function(f) {
var options = {};
form = $(this);
selector = form.attr('selector');
id = form.attr('id');
var _d = $.ajax({
url: '/status/' + selector + '/' + id,
method: 'GET',
success: function(data) {
var data = $(data)[0];
var switchInput = '#' + data.selector + '-' + data.id;
if (data.status == 'on') {
options.status = {
element: switchInput,
state: true
};
} else {
options.status = {
element: switchInput,
state: false
};
}
options.colour = {
element: '#' + data.id + '-colourpicker',
colour: data.colour
};
options.kelvin = {
element: '#' + data.id + '-kelvinpicker',
colour: data.colour
};
}
});
deferArr.push(_d)
triggers[counter] = options;
counter++;
})
$.when.apply($, deferArr).done(function() {
console.log(triggers); //can see all nested objects
console.log(triggers[0].colour); //returns null
console.log('triggers:' + JSON.stringify(triggers)); // can only see parent object
});

Here是在$ .when()中使用数组的引用。
foreach将推送所有延迟的数组,然后使用when数组的方法等待所有延迟的完成,然后执行done方法。