【问题标题】:JavaScript/jQuery: Divs not changing background color on loopJavaScript/jQuery:Divs 不会在循环中改变背景颜色
【发布时间】: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


【解决方案1】:

使用这个:

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

【讨论】:

  • 对不起,我编辑了那个。现在实际上有一个时期,但它仍然不起作用。
  • 请测试这个:$("#" + userId + " tbody tr td.page" + k).css("background-color", "green");
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 2013-04-28
  • 2014-06-21
  • 2014-04-21
  • 2021-01-23
  • 2011-06-15
相关资源
最近更新 更多