我试图在循环内的函数内正确访问IDs [i]的值。我尝试了以下内容。
我认为此方法将ID记录为字符串。我尝试使用索引访问它,但它未定义。请参阅simpleWithAttrPrice函数调用中的console.log。
for(i=0; i<IDs.length; i++)
{
console.log("Outside of function Vendor is " + IDs[i]);//logs correctly
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//"5,3"
console.log("Vendor is " + IDs[i]);//undefined
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
我也尝试将ID传递给回调函数,但它记录了“成功”(字面意思)
for(i=0; i<IDs.length; i++)
{
//var vendor = IDs[i];
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data, IDs) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//logs ID's as "success" ??
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
最后,我还尝试了以下内容,但它将价格追加到同一个区块。
for(i=0; i<IDs.length; i++)
{
var vendor = IDs[i];
var optionSelectionArray = currentlySelectedAttributes(vendor);
simpleWithAttrPrice(optionSelectionArray, function(data) {
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + vendor); //only logs this once.
$j('.details'+vendor+ ' .priceBlock').empty();//If I take this away, appends both prices to same block
$j('.details'+vendor+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}
如何在回调函数中正确访问数组ID?
答案 0 :(得分:0)
function sendRequest(i) {
var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
simpleWithAttrPrice(optionSelectionArray, function(data) {
//var vendor = IDs[i];
var basePrice = parseFloat(roundDollar(data));
//newPriceArray[vendor][colorSelected]=basePrice;
console.log("Vendor is " + IDs);//"5,3"
console.log("Vendor is " + IDs[i]);//undefined
$j('.details'+IDs[i]+ ' .priceBlock').empty();
$j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(basePrice,"$")+'</span>');
});
}//end sendRequest
for(i=0; i<IDs.length; i++)
{
sendRequest(i);
}