在$(document).ready()

时间:2016-07-13 08:35:55

标签: jquery

有人可以告诉我为什么以下代码中的函数f1(foo)f2(arr)没有在$(document).ready()中执行?

$(document).ready(function() {

var main = function() {
    var foo = //some text;
    var bar = //some text;

    var ARR = [];

    function f1(foo) {
        //matches foo with a reg exp and returns an array;
    }

    function f2(arr) {
        //loops through arr and pushes each element into ARR;
    }

    var Rfoo = f1(foo);
    var Rbar = f1(bar);

    if(/* condition */) {
        f2(Rfoo);
        f2(Rbar);
    }


    var imgArr = [];
    $('img[src *= "some-text"]').each(function() {
        var a = //something;
        var b = a.match(/* reg exp */)[0];
        imgArr.push(b);

        var formData = new FormData();
        formData.append(/* something to do with an apikey */);
        formData.append(/* something to do with b */);

        $.ajax({
            url: //something,
            data: formData,
            /*
            ...
            */
            success: function(data, textStatus, jqXHR) {
                var x = data["some-property"];

                if(x !== null) {
                    $.each(x, function(index, value) {
                        var m = value["property-1"]; //basically it is some text
                        // and a few more initializations...
                        console.log(m); // THIS LINE IS WORKING


                        // THE FOLLOWING 4 LINES OF CODE IS NEVER EXECUTED. WHY IS IT SO?
                        // functions f1, f2 are declared outside $(document).ready() so shouldn't it work inside 
                        // $(document).ready(). Am I doing something wrong here?
                        var Rbaz = f1(m);
                        if(Rbaz.length !== 0) {
                            f2(Rbaz);
                        }
                    })
                }
            },
            error: function(err) {
                //something;
            }
        });
    });

    return ARR;
}

var result = main();
console.log(result); // Showing an empty ARR...Why is it so?

});

我希望我能够让问题对读者显而易见。我想知道我是否以正确的方式构建整个代码。如果有的话,我愿意听取您的建议。谢谢!

0 个答案:

没有答案