简体   繁体   中英

JavaScript/jQuery: Divs not changing background color on loop

I'm currently working on an application where I call data from an API to see how much progress a student as made in an online journal. I'm using jQuery to create a table for each student to show their progress--basically, if the student has completed a certain page, there will be a element whose background color will now be green.

Here's an example of the type of API i'm working with:

[
{ "userId": 101,
  "name": "Student1",
  "lastPageCompleted": 5 },
{ "userId": 102,
  "name": "Student2",
  "lastPageCompleted": 3 },
{ "userId": 103,
  "name": "Student3",
  "lastPageCompleted": 4 }
]

Here is the code I'm currently working with:

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");
            }
        }
    })
}

Can anyone provide any pointers or suggestions as to why this wouldn't work? I should point out that when I try the following in Google Chrome, it actually does work. It just doesn't work in the function.

$("#" + userId + ".page" + k).css("background-color", "green");

use this:

$("#" + userId + " .page" + k).css("background-color", "green"); in jquery selector class names start with dot(.) and also you must use space between parent id and child class name to distinct them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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