Jquery为什么我不能显示对象?

时间:2014-08-15 06:59:01

标签: jquery arrays object

$(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] ??

,为什么我会收到错误

2 个答案:

答案 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将解决您的问题。