0

我正在做一个我在 MDN 网站上找到的练习,但我无法完成这个练习。重点是使用 JSON,从中提取数据,然后将其显示在页面上。代码有效,它按应有的方式生成字符串,我检查了控制台,一切正常。它只是不会将生成的字符串分配给已创建段落的 textContent 属性。当我在控制台中执行相同的任务时,它可以完美运行。

"""

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <section>

        </section>
        <script>
            const section = document.querySelector('section');


            let requestURL = "https://raw.githubusercontent.com/mdn/learning-area/master/javascript/oojs/tasks/json/sample.json";
            let request = new XMLHttpRequest();
            request.open("GET", requestURL);
            request.responseType = "json";
            request.send();


            let kittenInfo;
            let motherInfo = "The mothers are";


            request.onload = function() {
                let catString = request.response;
                extractInfo(catString);
            }

            function extractInfo(info){
                let end = ", ";;
                let total = 0;
                let male = 0;
                let names = "";

                for (let i = 0; i < info.length; i++) {
                    if (i === info.length - 2) {
                        end = " and";
                    }else if (i === info.length - 1){
                        end = ".";
                    }
                    motherInfo += " " + info[i].color + " " + info[i].breed + " " + info[i].name + end;

                    for (let j = 0; j < info[i].kittens.length; j++) {
                        end = ",";
                        if (i === info.length - 1) {
                            if (j === info[i].kittens.length - 2){
                                end = " and";
                            }else if (j === info[i].kittens.length - 1){
                                end = ".";
                            }
                        }

                        if (info[i].kittens[j].gender === "m"){
                            male += 1;
                        }

                        names += " " + info[i].kittens[j].name + end;
                        total += 1;
                    }
                }
                kittenInfo = `There are ${total} kittens, ${male} of them are male and ${total - male} of them are female. ` + 
                      `Their names are ${names}`;
            } 


            let para1 = document.createElement("p");
            let para2 = document.createElement("p");

            para1.textContent = motherInfo;
            para2.textContent = kittenInfo;

            section.appendChild(para1);
            section.appendChild(para2);

        </script>
    </body>
</html>
4

1 回答 1

0

在获得 HTTP 请求的响应之前,您正在设置文本内容。

您需要将para1.textContent = ...等移动到您的extractInfo()函数内部。

于 2020-10-25T20:50:53.553 回答