簡體   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