有人介意向我解释一下为什么吗...
$(document).ready(function() {
var scu = ['0291285', '0409338', '0521704', '0521990', '0523652', '0523657', '0523660', '0523704'];
var inData = $('#output');
var testdiv = $('#testdiv');
function Item(scu, description, price, extended, type) {
this.scu = scu;
this.description = description;
this.price = price;
this.extended = extended;
this.type = type;
//this.saved = function() {};
}
var rows = [];
function get() {
inData.html('');
$.each(scu, function(index, val) {
$.post('chBuild.php', {scu:val}, function(output) {
$.each(output, function(i, obj) {
var i = 0;
rows[i] = new Item(obj.scu, obj.description, obj.price, obj.extended, obj.type);
console.log(rows[i].price)
//this logs every object but...
i =+ 1;
});
}, 'json');
});
console.log(rows[0].price);
//this says rows[0] is undefined?
}
inData.click(get);
});
我正在尝试找到创建和存储多个对象的最佳方法。
最佳答案
$.post('chBuild.php', {scu:val}, function(output) {
$.each(output, function(i, obj) {
var i = 0;
rows[i] = new Item(obj.scu, obj.description, obj.price, obj.extended, obj.type);
console.log(rows[i].price)
i =+ 1;
});
}, 'json');
这里对 $.post 的调用是异步的,将在 ajax 调用返回时填充。也许你应该让它同步
$.ajax({'url': 'chBuild.php', 'async': false, ...);
关于javascript - 制作对象数组时的封装问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10867337/