$(function () {
setTimeout(function() {
var subcategory1 = $("body").find("#navCatLvl2 a");
var OdjSubcategory1 = {};
$(subcategory1).each(function(subcategory1,elem1) {
var num1 = subcategory1 + 1;
$(this).trigger('click');
var ArrOdjSubcategory1 = {
"SubCategoryId1" : num1,
"Name" : $(this).attr('data-text')
};
OdjSubcategory1[num1] = ArrOdjSubcategory1;
});
console.log('OdjSubcategory1 = ' + OdjSubcategory1);
}, 2000);
console.log(OdjSubcategory1);
});
我们收到错误:
ReferenceError:
OdjSubcategory1
未定义console.log(OdjSubcategory1);
如果console.log('OdjSubcategory1 = ' + OdjSubcategory1);
显示OdjSubcategory1 = [object Object]
??
答案 0 :(得分:1)
变量OdjSubcategory1
是本地的。
试试这个:
$(function () {
var OdjSubcategory1 = {};//<--- global now
setTimeout(function() {
var subcategory1 = $("body").find("#navCatLvl2 a");
$(subcategory1).each(function(subcategory1,elem1) {
var num1 = subcategory1 + 1;
$(this).trigger('click');
var ArrOdjSubcategory1 = {
"SubCategoryId1" : num1,
"Name" : $(this).attr('data-text')
};
OdjSubcategory1[num1] = ArrOdjSubcategory1;
});
console.log('OdjSubcategory1 = ' + OdjSubcategory1);
}, 2000);
console.log(OdjSubcategory1);
});
答案 1 :(得分:1)
您的console.log
存在于setTimeout
范围之外。 OdjSubcategory1
已不存在(超出范围)。
请参阅以下代码中的评论:
$(function () {
setTimeout(function() {
var subcategory1 = $("body").find("#navCatLvl2 a");
var OdjSubcategory1 = {};
$(subcategory1).each(function(subcategory1,elem1) {
var num1 = subcategory1 + 1;
$(this).trigger('click');
var ArrOdjSubcategory1 = {
"SubCategoryId1" : num1,
"Name" : $(this).attr('data-text')
};
OdjSubcategory1[num1] = ArrOdjSubcategory1;
});
console.log('OdjSubcategory1 = ' + OdjSubcategory1);
}, 2000); // The scope of everything declared within setTimeout ends here
console.log(OdjSubcategory1);
});
移动console.log
中的setTimeout
将解决您的问题。