开发者

Javascript: Arrays

For some reason开发者_如何学编程 my values are not being stored in the array:

var req = new Array();
$.get('./ajax/get_cat_info.php?cid=' +cid, function(data, textStatus) {
    var count = 0;
    $.each(data, function(key, val) {
        $('#' + key).show();
        if(val == 1) {
            req[count] = key;
            count = count + 1;
            //var arLen=req.length;
            //alert('l: ' + arLen); // this works though
        }
    });
}, 'json');

var arLen=req.length;
alert('l: ' + arLen);

I get alerted "l: 0" at the end. If I uncomment the line alert in the IF statement, it alerts on each one, then still alerts 0.


AJAX requests are, by default, asynchronous. You'll either have to change the AJAX request to be synchronous, or use the value of req in the callback.

In addition, you might want to use req.push(key) rather than using a count variable and req[count] = key; (although this isn't your problem).


The get call is running asynchronously, and so arLen=req.length is being evaluated prior to the function of elements being set actually completing. You can set the values accordingly from within the callback of the async call, as you determined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜