簡體   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