访问jQuery回调中的外部作用域

时间:2012-06-18 02:01:39

标签: javascript jquery scope jquery-callback

我有一种情况,我需要一个jQuery回调来处理它的范围之外的变量。为简单起见,假设以下代码:

$('#myBtn').on('click', function(e) {
    var num = 1;

    // assume this returns the following:
    // { success : true, num : 1 }
    $.getJSON('/api/get_number', {}, function(response) {
        if ( response.success ) {
            // here, num is unknown unless I define it as a
            // global variable
            num += response.num ;   
        }
    });

    console.log(num); // => want 2, get 1
});

我希望num在回调函数中可用。如果不声明全局变量(在o​​nclick函数之外声明num),这样做的好方法是什么?有没有办法将它作为参数传递而不必从服务器发送它?感谢。

1 个答案:

答案 0 :(得分:-1)

$('#myBtn').on('click', function(e) {
    var num = 1;

    // assume this returns the following:
    // { success : true, num : 1 }
    $.getJSON('/api/get_number', {}, function(response) {
        // get responce
        if ( response.success ) {
            // here, num is unknown unless I define it as a
            // global variable
            num += response.num ;   
            console.log(num); // you will get 2 here
        }
    });
    // responce havnt get ,you always get 1
    console.log(num); // => want 2, get 1
});
相关问题