我有以下内容:
function builTable(){
for(i = 0; i< source.Products.length; i++){
var sourceProducts = source.Products[i];
row = '<tr><td>sth</td><td>';
row += sourceProducts.Product;
row += '</td><td>';
row += sourceProducts.Bookings + '</td><td>';
row += sourceProducts.Percentage + '%' + '</td><td>';
row += sourceProducts.Transactions + '</td></tr>';
return row;
}
}
function generateTable(){
$('table').append(builTable());
}
$(document).ready(function(){
generateTable();
});
这只会附加表格的第一行,但如果我将其更改为以下内容:
function builTable(){
for(i = 0; i< source.Products.length; i++){
var sourceProducts = source.Products[i];
row = '<tr><td>sth</td><td>';
row += sourceProducts.Product;
row += '</td><td>';
row += sourceProducts.Bookings + '</td><td>';
row += sourceProducts.Percentage + '%' + '</td><td>';
row += sourceProducts.Transactions + '</td></tr>';
$('table').append(row);
}
}
$(document).ready(function(){
builTable();
});
它工作正常,我希望有一个更结构化的代码,其功能可以满足其目的:
JSON格式:
var source = {
"Products": [
{
"Product": "xxxxx.com",
"Bookings": 560,
"Percentage": 55.82,
"Transactions": "xxxx.xx"
},
{
"Product": "xxxxx Mobile",
"Bookings": 487,
"Percentage": 9.12,
"Transactions": "xxxx.xx"
},
{
"Product": "xx 24-7",
"Bookings": 478,
"Percentage": 8.95,
"Transactions": "xxxx.xx"
},
{
"Product": "xxxxxx",
"Bookings": 422,
"Percentage": 7.9,
"Transactions": "xxxx.xx"
},
{
"Product": "API",
"Bookings": 315,
"Percentage": 5.9,
"Transactions": "xxxx.xx"
},
{
"Product": "API",
"Bookings": 315,
"Percentage": 2.83,
"Transactions": "xxxx.xx"
}
],
"Total": {
"Bookings": 315,
"Transactions": "xxxx.xx"
}
}
任何帮助?
答案 0 :(得分:1)
function builTable(){
var table = "";
for(i = 0; i< source.Products.length; i++){
var sourceProducts = source.Products[i],
row = '<tr><td>sth</td><td>';
row += sourceProducts.Product;
row += '</td><td>';
row += sourceProducts.Bookings + '</td><td>';
row += sourceProducts.Percentage + '%' + '</td><td>';
row += sourceProducts.Transactions + '</td></tr>';
table += row;
}
return table;
}
function generateTable(){
$('table').append(builTable());
}
$(document).ready(function(){
generateTable();
});
答案 1 :(得分:1)
这是因为每次循环重新开始时row
都会重置。
function builTable(){
for(i = 0; i< source.Products.length; i++){
var sourceProducts = source.Products[i];
// here is the culprit
row = '<tr><td>sth</td><td>';
row += sourceProducts.Product;
row += '</td><td>';
row += sourceProducts.Bookings + '</td><td>';
row += sourceProducts.Percentage + '%' + '</td><td>';
row += sourceProducts.Transactions + '</td></tr>';
return row;
}
}