jQuery .push进入.get调用中的数组会产生一个空结果 [英] jQuery .push into an Array in a .get call gives an empty result

查看:232
本文介绍了jQuery .push进入.get调用中的数组会产生一个空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么下面给我一个空字符串?当 console.log(contentArray) $。get()回调函数中时,它会显示数据,但是当我尝试在下面的代码中执行此操作,结果为空。

Can anyone tell me why the below gives me an empty string? When I console.log(contentArray) in the $.get() callback function it shows the data but when I try to do it where it is in the code below, the result is empty.

sectionArray = [];
contentArray = [];
$(function () {
    if (index == 1) {
        $('menu:eq(' + (section - 1) + ') li a').each(function () {
            sectionArray.push($(this).attr('href'));
        });

        var len = sectionArray.length;

        for (var i = 0; i < len; i++) {
            href2 = sectionArray[i];

            $.get(href2, function (data) {
                string = data.toString();
                contentArray.push(string);
            });
        }
        content = contentArray.toString();
        console.log(content);
    }


推荐答案

因为ajax请求在你调用 console.log()之后结束试试这个:

because ajax request ends after you call console.log() try this:

$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    content = contentArray.toString();
    console.log(content);
});

在循环中做ajax请求也不是最好的事情。那不会按你的意愿工作。

also do ajax request in loop is not best thing to do. that wont work as you want.

UPDATE:

jQuery还有 async 选项设置为false,您的代码应该可以正常运行但速度很慢。同步请求可能会暂时锁定浏览器。

also jQuery has async option set to false and your code should work but will work slow. Synchronous requests may temporarily lock the browser.

更新2

也许可以试试像这样(也许不是那么好主意:D):

maybe try something like this(maybe not so good idea :D):

var countRequests = len;
$.get(href2, function(data){
    string = data.toString();
    contentArray.push(string);
    countRequests = countRequests - 1;
    if (countRequests == 0) {
        content = contentArray.toString();
        console.log(content);
        // or create callback
    }
});

这篇关于jQuery .push进入.get调用中的数组会产生一个空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆