【发布时间】:2019-03-24 05:35:28
【问题描述】:
我目前正在开发一个应用程序,在该应用程序中我从 API 调用数据,以查看学生在在线日记中取得了多少进步。我正在使用 jQuery 为每个学生创建一个表格来显示他们的进度——基本上,如果学生完成了某个页面,就会有一个元素的背景颜色现在为绿色。
这是我正在使用的 API 类型的示例:
[
{ "userId": 101,
"name": "Student1",
"lastPageCompleted": 5 },
{ "userId": 102,
"name": "Student2",
"lastPageCompleted": 3 },
{ "userId": 103,
"name": "Student3",
"lastPageCompleted": 4 }
]
这是我目前正在使用的代码:
function getHighestPageCompleted() {
$.ajax({
url: "www.exampleapi.com/studentProgress",
dataType: "json"
}).done(function(data) {
for (let i=0; i < data.length; i++) {
let name = data[i].name;
let lastPageCompleted = data[i].lastPageCompleted;
let userId = data[i].userId;
//here, the function loops through and creates tables with ids that match the userId, and td that haves classes of page1, page2, page3, page4, and page5
let studentDashboard = ('<table id="' + userId + '"><tbody><tr><th>' + name + '</th><td class=\'page1\'></td><td class=\'page2\'></td><td class=\'page3\'></td><td class=\'page4\'></td><td class=\'page5\'></td></tr></table>');
//in a separate HTML file, a class called 'dashboardContainer' receives the studentDashboards
$(".dashboardContainer").append(studentDashboard);
//here's the part that is tricking me up -- I need to change the background color of each td according to how many pages they've finished
//this function is supposed to loop through each newly created table and color the background of each finished page div to green
for (let k=0; k < lastPageCompleted; k++) {
$("#" + userId + ".page" + k).css("background-color", "green");
}
}
})
}
任何人都可以就为什么这不起作用提供任何指示或建议吗?我应该指出,当我在 Google Chrome 中尝试以下操作时,它确实有效。它只是在函数中不起作用。
$("#" + userId + ".page" + k).css("background-color", "green");
【问题讨论】:
-
试试
$(".dashboardContainer").find("#" + userId + "page" + k).css() -
如果
$("#" + userId + "page" + k).css("background-color", "green");有效,您确定ajax 调用正在完成并到达done?
标签: javascript jquery css ajax loops