我想延迟 i++ 直到 jquery 回调完成。我有这个:
for (var i = 0; i < stocks.length; i++) {
var lastprice = 0
var stock = stocks[i].stock;
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("' + stock + '")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
function(data) {
lastprice = data.query.results.quote.LastTradePriceOnly;
}).done(function() {
console.log(stock, lastprice);
});
};
问题是循环在 .getJSON 之前完成,所以我最终只是在控制台记录了我数组中的最后一只股票,但是我的数组中所有股票的价格。我试过了,但它只会杀死我的浏览器:
for (var i = 0; i < stocks.length;) {
var lastprice = 0
var stock = stocks[i].stock;
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("' + stock + '")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys',
function(data) {
lastprice = data.query.results.quote.LastTradePriceOnly;
}).done(function() {
console.log(stock, lastprice);
i++;
});
};
有人知道我在做什么错吗?谢谢!