简体   繁体   English

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

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

I'm using jQuery to parse an XML file, and I'm trying to push each element in the XML file to an array using a jQuery .each loop. 我正在使用jQuery来解析XML文件,我正在尝试使用jQuery .each循环将XML文件中的每个元素推送到数组。 Strangely, if I alert the value of the array within the loop it comes out as it should, but if I try to alert a value in the array after the loop has finished it results in "undefined". 奇怪的是,如果我在循环中警告数组的值它应该出现,但是如果我在循环结束后尝试警告数组中的值,则会导致“未定义”。

Is there something strange that happens when you push values to an array within this kind of a loop? 在这种循环中将值推送到数组时会发生什么奇怪的事情吗?


Here is the Javascript: 这是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



Here is the XML: 这是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>

Correct variant: 正确的变种:

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]);
});

In your variant of code alert(splashArray[1]); 在您的代码变体alert(splashArray [1]); executes before ajax get xml result, therefore splashArray was empty, when you try to alert element with index 1. Your code works well only for synchronous mode, when thread waits for server response. 在ajax获取xml结果之前执行,因此当您尝试使用索引1警告元素时,splashArray为空。当线程等待服务器响应时,您的代码仅适用于同步模式。 In Asynchronous mode you should use callback function. 在异步模式下,您应该使用回调函数。

Variant with callback: 变量回调:

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]);
}

Or one more pattern (pseudocode): 或者一个模式(伪代码):

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

You are alerting before the array is being populated. 在填充阵列之前,您正在发出警报。 You need to understand that XHR/Ajax is asynchronous ( as opposed to synchronous ) so the alert will not always run after the callback function because it will take a few seconds to do the actual HTTP request to grab the xml, alerting inside the callback ensures that it is populated after the XHR stuff is done. 您需要了解XHR / Ajax是异步的(而不是同步的),因此警报不会总是在回调函数之后运行,因为执行实际的HTTP请求需要几秒钟来获取xml,在回调内部进行警报确保在完成XHR之后填充它。

Works: 作品:

var splashArray = [];

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

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

Doesn't work: 不起作用:

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