在$ .each()函数之外访问JavaScript变量

时间:2014-04-02 22:11:57

标签: javascript jquery

我无法将$ .each()函数中声明的变量传递给Prototype函数。我收到错误Uncaught ReferenceError: prices is not defined

Compare.prototype.results = function (answers) {

    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
            answers: answers
        },

        success: function (data) {

            $.each(data, function (index, dataItem) {

                var prices = [],
                    priceData = dataItem.pricing_term,
                    priceObj = JSON.parse(priceData);

                $.each(priceObj, function (term, pricing) {
                    prices.push(term, pricing);
                });

            });
            Compare.prototype.show(data, prices);
        }

    });
}

我希望能够填充价格变量并将其传递给最初从ajax调用返回的数据。我是javascript的新手,如果有更清晰的方式来写这个请告诉我。

2 个答案:

答案 0 :(得分:1)

超出范围

Compare.prototype.results = function (answers) {

    $.ajax({
        type: 'POST',
        dataType: 'json',
        data: {
            answers: answers
        },

        success: function (data) {

            var prices = [];


            $.each(data, function (index, dataItem) {
                var priceData = dataItem.pricing_term,
                    priceObj = JSON.parse(priceData);

                $.each(priceObj, function (term, pricing) {
                    prices.push(term, pricing);
                });

            });

            // same scope

            Compare.prototype.show(data, prices);
        }

    });
}

答案 1 :(得分:1)

您已在第一个prices函数的范围内声明了您的&.each数组。这意味着您只能访问该函数中的prices数组。您需要在函数之外声明prices,如下所示:

Compare.prototype.results = function (answers) {

$.ajax({
    type: 'POST',
    dataType: 'json',
    data: {
        answers: answers
    },

    success: function (data) {

        var prices = [];

        $.each(data, function (index, dataItem) {

               var priceData = dataItem.pricing_term;
               var priceObj = JSON.parse(priceData);

            $.each(priceObj, function (term, pricing) {
                prices.push(term, pricing);
            });

        });
        Compare.prototype.show(data, prices);
    }

});
}

这样,prices可用于AJAX请求的success函数范围内的任何函数。