繁体   English   中英

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

[英]JavaScript/jQuery: Divs not changing background color on loop

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

用这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM