繁体   English   中英

在每个循环中推送到jQuery中的数组

[英]Pushing to an Array within a jQuery each loop

我正在使用jQuery来解析XML文件,我正在尝试使用jQuery .each循环将XML文件中的每个元素推送到数组。 奇怪的是,如果我在循环中警告数组的值它应该出现,但是如果我在循环结束后尝试警告数组中的值,则会导致“未定义”。

在这种循环中将值推送到数组时会发生什么奇怪的事情吗?


这是Javascript:

var splashArray = new Array();

// Load the Splash XML file and assign each image within to an array
$.get('splash.xml', function(xml) {
    $('image', xml).each(function (i) {
        splashArray.push($(this).attr("src"));
    });
});

alert(splashArray[1]); // Results in undefined



这是XML:

<?xml version="1.0" encoding="UTF-8"?>
<site>      
    <image src="splash1.jpg" />
    <image src="splash2.jpg" />
    <image src="splash3.jpg" />
    <image src="splash4.jpg" />
    <image src="splash5.jpg" />
    <image src="splash6.png" />
</site>

正确的变种:

var splashArray = new Array();

// Load the Splash XML file and assign each image within to an array
$.get('splash.xml', function(xml) {
        $('image', xml).each(function (i) {
                splashArray.push($(this).attr("src"));
        });
        alert(splashArray[1]);
});

在您的代码变体alert(splashArray [1]); 在ajax获取xml结果之前执行,因此当您尝试使用索引1警告元素时,splashArray为空。当线程等待服务器响应时,您的代码仅适用于同步模式。 在异步模式下,您应该使用回调函数。

变量回调:

var splashArray = new Array();

// Load the Splash XML file and assign each image within to an array
$.get('splash.xml', function(xml) {
        $('image', xml).each(function (i) {
                splashArray.push($(this).attr("src"));
        });
        work_with_splash();
});

function work_with_splash () {
    alert(splashArray[1]);
}

或者一个模式(伪代码):

function process(ajax_is_done) {
    if (!ajax_is_done) {
        ajax(function (result) {
            import_result(result);
            process(true);
        })
    }
}
process();

在填充阵列之前,您正在发出警报。 您需要了解XHR / Ajax是异步的(而不是同步的),因此警报不会总是在回调函数之后运行,因为执行实际的HTTP请求需要几秒钟来获取xml,在回调内部进行警报确保在完成XHR之后填充它。

作品:

var splashArray = [];

function fn() {
    alert(splashArray[1]);
}

$.get('splash.xml', function(xml) {
        $('image', xml).each(function (i) {
                splashArray.push($(this).attr("src"));
        });
        fn();
});

不起作用:

var splashArray = [];

$.get('splash.xml', function(xml) {
        $('image', xml).each(function (i) {
                splashArray.push($(this).attr("src"));
        });
        // this will populate the array almost always AFTER the alert below.
});


alert(splashArray[1]); // this will almost ALWAYS alert BEFORE the callback function is done

如果您不想使用标准回调,则另一个选项是触发jQuery事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM