我正在使用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
Run Code Online (Sandbox Code Playgroud)
这是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>
Run Code Online (Sandbox Code Playgroud)
Ana*_*liy 13
正确的变种:
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]);
});
Run Code Online (Sandbox Code Playgroud)
在您的代码变体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]);
}
Run Code Online (Sandbox Code Playgroud)
或者一个模式(伪代码):
function process(ajax_is_done) {
if (!ajax_is_done) {
ajax(function (result) {
import_result(result);
process(true);
})
}
}
process();
Run Code Online (Sandbox Code Playgroud)