【发布时间】:2014-08-01 04:23:56
【问题描述】:
我对对象 dict 有疑问。当接收到 json 数据时,程序会调用 LoadDict() 函数,其中 dict 对象会被来自服务器的新数据填充。我使用 FireBug 来确保 dict 包含具有正确信息的所有新元素,但是当函数完成时,dict 再次变为空,就像在 ajax 请求之前一样。此代码在全局范围内执行:
var dict = new Dictionary();
function LoadDict(words) {
for (var i in words) {
var word = new Word();
word.word = words[i].Word;
word.transcript = words[i].Transcript;
word.frequency = words[i].Frequency;
word.meanings = words[i].Meanings;
word.examples = words[i].Examples;
word.imgLinks = words[i].ImgLinks;
dict.Add(word);
}
}
$.getJSON("getall").done(LoadDict);
dict.PrintDictionary);
这是我的 Dictionary 类的一些代码
function Dictionary() {
this.collection = new Array();
this.count = 0;
this.sorted = false;
}
Dictionary.prototype.Add = function(word) {
if (word instanceof Word) {
word.id = this.count;
this.collection[this.count] = word;
this.count++;
this.sorted = false;
}
}
Dictionary.prototype.PrintDictionary = function() {
function WordToString(word) {
var line = "<strong>" + word.word + "</strong> [" + word.transcript + "] - " + word.meanings[0];
for (var j = 1; j < word.meanings.length; j++) {
line += ", " + word.meanings[j];
}
return line;
}
var result = "<ol>"
for (var i = 0; i < this.collection.length; i++)
result += "<li>" + WordToString(this.collection[i]) + "</li>";
result += "</ol>"
document.write(result);
}
Dictionary 类的声明在创建 dict 对象之前进行。 请帮忙!
【问题讨论】:
-
也许你可以试试同步调用
标签: javascript jquery json scope javascript-objects