繁体   English   中英

如何使用 Javascript 和 JSON 生成 HTML 代码?

[英]How to generate HTML code using Javascript and JSON?

我需要通过解析 JSON 文件来创建测验。 检查的答案必须存储在本地存储中。

JSON代码:

{
    "quiz": {
        "q1": {
            "question": "Which one is correct team name in NBA?",
            "options": [
                "New York Bulls",
                "Los Angeles Kings",
                "Golden State Warriros",
                "Huston Rocket"
            ],
            "answer": "Huston Rocket"
        },
        "q2": {
            "question": "'Namaste' is a traditional greeting in which Asian language?",
            "options": [
                "Hindi",
                "Mandarin",
                "Nepalese",
                "Thai"
            ],
            "answer": "Hindi"
        },
        "q3": {
            "question": "The Spree river flows through which major European capital city?",
            "options": [
                "Berlin",
                "Paris",
                "Rome",
                "London"
            ],
            "answer": "Berlin"
        },
        "q4": {
            "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?",
            "options": [
                "Pablo Picasso",
                "Vincent van Gogh",
                "Salvador Dalí",
                "Edgar Degas"
            ],
            "answer": "Pablo Picasso"
        }
    }
}

代码如下:

<div id="container"></div>
    <input type ="submit" name ="submit" value = "Submit answers" onclick = "results()">
    <script>
        let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}};
        let list = document.createElement("ul");
        for (let questionId in data["quiz"]) {
            let item = document.createElement("node");
            let question = document.createElement("strong");
            question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"];
            item.appendChild(question);
            list.appendChild(item);
            let sublist = document.createElement("ul");
            item.appendChild(sublist);
            for (let option of data["quiz"][questionId]["options"]) {
                item = document.createElement("input");
                item.type = "radio";
                item.name = data["quiz"][questionId];
                var label = document.createElement("label");
                label.htmlFor = "options";
                label.appendChild(document.createTextNode(data["quiz"][questionId]["options"]));
                var br = document.createElement('br');
                sublist.appendChild(item);
                document.getElementById("container").appendChild(label);
                document.getElementById("container").appendChild(br); 
            }                      
        }
        document.getElementById("container").appendChild(list);     
        function results () {
            var score = 0;
            if (data["quiz"][questionId]["answer"].checked) {
                score++;
            }
        }
        localStorage.setItem("answers","score");
    </script>    

我应该得到这个:

在此处输入图像描述

相反,无论我重写代码多少次,我都得到了这个:

在此处输入图像描述

我为什么做错了?

非常感谢您的帮助,

玛丽。

document.createElement("node")有一个小错误 - 没有标记node ,因此向其附加其他元素也是不正确的。 代码可以简化如下(尽管添加到本地存储会在代码片段中引发错误)

 let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; // utility prototype to shuffle an array Array.prototype.shuffle=()=>{ let i = this.length; while (i > 0) { let n = Math.floor(Math.random() * i); i--; let t = this[i]; this[i] = this[n]; this[n] = t; } return this; }; let list = document.createElement("ul"); Object.keys(data.quiz).forEach((q, index) => { // the individual record let obj = data.quiz[q]; // add the `li` item & set the question number as data-attribute let question = document.createElement("li"); question.textContent = obj.question; question.dataset.question = index + 1; question.id = q; // randomise the answers obj.options.shuffle(); // Process all the answers - add new radio & label Object.keys(obj.options).forEach(key => { let option = obj.options[key]; let label = document.createElement('label'); label.dataset.text = option; let cbox = document.createElement('input'); cbox.type = 'radio'; cbox.name = q; cbox.value = option; // add the new items label.appendChild(cbox); question.appendChild(label); }); // add the question list.appendChild(question); }); // add the list to the DOM document.getElementById('container').appendChild(list); // Process the checked radio buttons to determine score. document.querySelector('input[type="button"]').addEventListener('click', e => { let score = 0; let keys = Object.keys(data.quiz); document.querySelectorAll('[type="radio"]:checked').forEach((radio, index) => { if( radio.value === data.quiz[ keys[index] ].answer ) score++; }); console.log('%d/%d', score, keys.length); localStorage.setItem("answers", score); })
 #container>ul>li { font-weight: bold } #container>ul>li>label { display: block; padding: 0.1rem; font-weight: normal; } #container>ul>li>label:after { content: attr(data-text); } #container>ul>li:before { content: 'Question 'attr(data-question)': '; color: blue }
 <div id="container"></div> <input type="button" value="Submit answers" />

您需要对嵌套循环进行细微更改,以便将选项标签插入正确的位置。 查看标记为“删除”和“添加”的代码片段,了解您需要进行的更改。

正如@ProfessorAbronsius 指出的那样,没有名为“节点”的 html 标签,尽管这不会阻止您的代码正常工作。

 let data = {"quiz": {"q1": {"question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket"}, "q2": {"question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi"}, "q3": {"question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin"}, "q4": {"question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso"}}}; let list = document.createElement("ul"); for (let questionId in data["quiz"]) { let item = document.createElement("node"); let question = document.createElement("strong"); question.innerHTML = questionId + ": " + data["quiz"][questionId]["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); // The problem is here in this nested loop for (let option of data["quiz"][questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = data["quiz"][questionId]; var label = document.createElement("label"); label.htmlFor = "options"; // remove 1 // label.appendChild(document.createTextNode(data["quiz"][questionId]["options"])); // add 1 label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); // remove 2 //document.getElementById("container").appendChild(label); //document.getElementById("container").appendChild(br); // add 2 sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data["quiz"][questionId]["answer"].checked) { score++; } } // Removed because snippets don't allow localStorage // localStorage.setItem("answers", "score");
 <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()">

这是您问题的答案。 如果您有任何问题,请告诉我。

 <div id="container"></div> <input type="submit" name="submit" value="Submit answers" onclick="results()"> <script> let data = { "quiz": { "q1": { "question": "Which one is correct team name in NBA?", "options": ["New York Bulls", "Los Angeles Kings", "Golden State Warriros", "Huston Rocket"], "answer": "Huston Rocket" }, "q2": { "question": "'Namaste' is a traditional greeting in which Asian language?", "options": ["Hindi", "Mandarin", "Nepalese", "Thai"], "answer": "Hindi" }, "q3": { "question": "The Spree river flows through which major European capital city?", "options": ["Berlin", "Paris", "Rome", "London"], "answer": "Berlin" }, "q4": { "question": "Which famous artist had both a 'Rose Period' and a 'Blue Period'?", "options": ["Pablo Picasso", "Vincent van Gogh", "Salvador Daly", "Edgar Degas"], "answer": "Pablo Picasso" } } }; data = data.quiz; let list = document.createElement("ul"); for (let questionId in data) { let item = document.createElement("node"); let question = document.createElement("strong"); let i = Object.keys(data).indexOf(questionId) + 1; question.innerHTML = "Question" + i + ": " + questionId["question"]; item.appendChild(question); list.appendChild(item); let sublist = document.createElement("ul"); item.appendChild(sublist); for (let option of data[questionId]["options"]) { item = document.createElement("input"); item.type = "radio"; item.name = questionId; var label = document.createElement("label"); label.htmlFor = option; label.appendChild(document.createTextNode(option)); var br = document.createElement('br'); sublist.appendChild(item); sublist.appendChild(label); sublist.appendChild(br); } } document.getElementById("container").appendChild(list); function results() { var score = 0; if (data[questionId]["answer"].checked) { score++; } } //localStorage.setItem("answers", "score"); </script>

暂无
暂无

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

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