$(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]
为什么会出现错误? 最佳答案
您的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
将解决您的问题。关于jquery - jQuery为什么我无法显示对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25322417/