JavaScript / jQuery:Divs不会在循环中更改背景颜色

时间:2019-03-24 05:35:28

标签: javascript jquery css ajax loops

我目前正在开发一个应用程序,该应用程序从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");

1 个答案:

答案 0 :(得分:2)

使用此:

$("#" + userId + " .page" + k).css("background-color", "green"); 在jquery选择器中,类名以点号(。)开头,并且还必须在父ID和子类名之间使用空格来区分它们。