我遇到了一个非常奇怪的问题。我正在使用 jQuery 的 $.get 从 URL 检索 XML。获得 XML 后,我将解析 id
、title
和 content
属性。然后,我将每个添加到一个对象中。
由于某种原因,仅在 Google Chrome 中(我在 IE 或 Firefox 中没有问题),在将保存内容的变量插入对象之前,它是空的。但是在我解析该值并将其分配给该变量后,该变量就具有正确的值。这是我的代码,请参阅评论。
var myarray = new Array();
$.get( "https://www.my-url.com", function( data ) {
$(data).find('entry').each(function(){
var id, title, content;
$(this).find("id").each(function(){
var id = $(this).text();
});
$(this).find("title").each(function(){
title = $(this).text();
});
$(this).find("content").each(function(){
content = $(this).text();
console.log(content); // value of content is correct
});
console.log(content); // value of content is empty
var o=new myobject(id,title,content);
myarray.push(o);
});
});
发生什么事了?
最佳答案
在给定场景中无需使用each() 循环。
使用
var $this = $(this),//cached jQuery object
id = $this.find("id").text(),
title = $this.find("title").text(),
content = $this.find("content").text();
关于仅在 Google Chrome 中解析 XML 后 JavaScript 变量失去值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896920/