Javascript 如何从外部JSON文件中随机抽取一些数据并在页面中显示它们?
我试图实现这样一种情况,即加载JSON数据时,只会从数据源中提取并显示随机设置的数据量,例如10、20或30等,而不会出现任何重复,而不是当前加载整个数据时发生的情况。 此外,目前我有20多个单独的JSON文件,在某些情况下,数据量从10到350不等 您将从我的JScript代码中注意到,页面加载后,只会加载一个JSON文件。每当我需要加载任何其他JSON数据文件时,我必须求助于将Javascript 如何从外部JSON文件中随机抽取一些数据并在页面中显示它们?,javascript,arrays,json,random,Javascript,Arrays,Json,Random,我试图实现这样一种情况,即加载JSON数据时,只会从数据源中提取并显示随机设置的数据量,例如10、20或30等,而不会出现任何重复,而不是当前加载整个数据时发生的情况。 此外,目前我有20多个单独的JSON文件,在某些情况下,数据量从10到350不等 您将从我的JScript代码中注意到,页面加载后,只会加载一个JSON文件。每当我需要加载任何其他JSON数据文件时,我必须求助于将myQuizUrl中的文件名从tricky|u streets.JSON更改为schools.JSON等。 我
myQuizUrl
中的文件名从tricky|u streets.JSON
更改为schools.JSON
等。
我相信有一种方法可以创建一个按钮,当单击该按钮时,它将移动到另一个页面,并在另一个页面中加载其他JSON数据,或者用当前页面中的新集合替换当前数据。如果可能的话,这两种解决方案都是理想的,因为我可以在以后决定使用哪一种。
我还想添加一个候选人的名字,如“John Doe”,在这里,进度和分数将被跟踪和存储,并可在以后检索。然而,我理解这可能会证明是困难和繁重的。
我提供了一些代码片段:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<header>
<h1>City Council</h1>
<h2>Location Knowledge Mock Test:</h2>
<h3><span class='quiz-title'>Quiz Title</span></h3>
<div id="stats-div">
<div id="result">Score = <span id="selected"></span></div> <div id="notchecked">Remaing Questions or Not Answered = <span id="unselected"></span></div>
<!-- Counting only worked after JS code was moved from the 'head' tag to the bottom of the body tag -->
<div id="totalquestions">Total Amount Of Questions = <span id="num-of-questions"></span></div> <!-- ids swapped around -->
<div><strong>Score Percentage</strong> <span id="score-perc" style="color: green; font-size: 1.5em;"></span> <strong>%</strong></div>
<div id="perScoreDiv">
</div>
<input type="button" id="tick-all-btn" onclick="checkAll2()" class="btn btn-link" value="Tick All Answers">
<input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset Test">
</div>
</header>
<div id="wrapper">
<div id="q-wrapper">
<form>
</form>
</div>
</div>
<script src="script.js"> </script>
</body>
</html>
第一件事:JScript已经不存在了。微软曾经拥有一种叫JScript的JavaScript方言,但现在它不再在任何浏览器中使用了。我认为如果你的问题更集中,你会得到更好的答案。我在这里看到了至少3个问题:1)如何随机选择Javascript数据结构的部分2)如何确保没有重复3)如何仅加载大型数据集的一部分。你能简化你的问题吗?
const buildQuestion = function(title, category, {name, value}){
return document.createRange().createContextualFragment(`<label class='q-texts'><input type='checkbox' class='check2 ${category}' name='${title}' value='${value}'/> ${name}</label>`);
}
const buildCategory = function(title, category){
const categoryEl = document.createElement("formset");
const legendEl = document.createElement("legend");
legendEl.textContent = category;
categoryEl.appendChild(legendEl);
return categoryEl;
}
const buildQuiz = function(JSONUrl){
/***
* the JSONurl parameter is the url of the file
* containing the entirety of the quiz data.
*/
const quizEl = document.querySelector("form");
const headerEl = document.querySelector("header");
const titleEl = headerEl.querySelector(".quiz-title");
fetch(JSONUrl)
.then(response => response.json() )
.then(quizObject =>{
titleEl.textContent = quizObject.title;
quizObject.categories.forEach(function({category, questions}){
const categoryEl = buildCategory(quizObject.title, category);
questions.forEach( function(question){
const questionEl = buildQuestion(quizObject.title, category, question);
categoryEl.appendChild(questionEl);
})
quizEl.appendChild(categoryEl);
})
document.querySelector("#num-of-questions").textContent = quizEl.querySelectorAll("input[type='checkbox']").length;
// Count Unticked boxes
quizEl.addEventListener("change", ()=>{
const uncheckedEls = quizEl.querySelectorAll("input[type='checkbox']:not(:checked)").length;
document.querySelector("#unselected").textContent = uncheckedEls;
// Counts ticked boxes
const checkedEls = quizEl.querySelectorAll("input[type='checkbox']:checked").length; // Added in by me
document.querySelector("#selected").textContent = checkedEls; // Added in by me
// Score percentage
const totalEls = Number(document.querySelector("#num-of-questions").textContent);
document.querySelector("#score-perc").textContent = Number(((totalEls-uncheckedEls)/totalEls )*100).toFixed(2);
})
})
}
/***
* Here is where we actually call the quiz building
* parts. This gets the JSON data, and builds the form
* dynamically. Change this to:
* "./JSON/schools.json",
* "./JSON/dental-surgeries.json" or
* "./JSON/veterinarians.json"
* to view the same quiz template with different data.
*/
let myQuizParam = window.location.search.toString().match(/(\?quiz=)([a-z0-9\-]*)/i );
let myQuizUrl = "";
console.log(JSON.stringify(myQuizParam));
if (myQuizParam && myQuizParam.length > 0){
myQuizUrl = `./JSON/${myQuizParam[2]}.json`;
} else {
myQuizUrl = `./JSON/tricky_streets.json`;
}
buildQuiz(myQuizUrl);
// Reset test and Check all checkboxes
//v2 Tick all Checkboxes
function checkAll2() {
var inputs = document.querySelectorAll('.check2');
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = true;
inputs[i].dispatchEvent(new Event("change", {bubbles: true}))
}
}
// Untick All Checkboxes
function uncheckAll2() {
var inputs = document.querySelectorAll('.check2');
for(var i = 0; i < inputs.length; i++) {
inputs[i].checked = false;
inputs[i].dispatchEvent(new Event("change", {bubbles: true}))
}
}
{
"title": "Tricky Streets Withinin City Boundries",
"categories": [
{
"category": "Local",
"questions": [
{
"name": "Chessman Court: Estcort Rd",
"value": "TSWICB:TCBS01"
},
{
"name": "Pegotty Bungalows: Stanway Rd",
"value": "TSWICB:TCBS02"
},
{
"name": "Mendip Cl: Chiltern Rd",
"value": "TSWICB:TCBS03"
},
{
"name": "Brecon Cl: Chiltern Rd",
"value": "TSWICB:TCBS04"
},
{
"name": "Quantock Rd: Fieldcourt Dr",
"value": "TSWICB:TCBS05"
},
{
"name": "Cheviout Cl: Quantock Rd",
"value": "TSWICB:TCBS06"
},
{
"name": "Graham Gdns: Estcort Rd",
"value": "TSWICB:TCBS91"
}
]
}
]
}
{
"title": "Schools",
"categories": [
{
"category": "Infants",
"questions": [
{
"name": "Churchdown Infant School: Station Rd (Churchdon)",
"value": "CIS:SR"
},
{
"name": "Longlevens Infant School: Paygrove Ln",
"value": "LIS:PL"
},
{
"name": "Tredworth Infant School: Victory Rd",
"value": "TIS:VR"
},
{
"name": "Dinglewell Infant School: Dinglewell",
"value": "DIS:DW"
},
{
"name": "Innsworth Infant School: Luke Ln",
"value": "IIS:LN"
},
{
"name": "Churchdown Village Infant School: Station Rd (Churchdon)",
"value": "CVS:SR"
},
{
"name": "Churchdown Parton Manor Infant School: Craven Drive (Churchdown)",
"value": "CPMI:CD"
}
]
}
]
}
{
"title": "Pubs",
"categories": [
{
"category": "Local",
"questions": [
{
"name": "Brew House And Kitchen: Quays",
"value": "BHK:QY"
},
{
"name": "Dr Foster: Kimberley Warehouse (The Docks)",
"value": "DFR:TD"
},
{
"name": "The Lord High Constable: Llanthony Warehouse (Wetherspoon)",
"value": "TLHC:LW"
},
{
"name": "Wheatstone Inn: Centre Severn",
"value": "WSI:CS"
},
{
"name": "Tank: Llanthony Rd (Wetherspoon)",
"value": "TNK:LR"
},
{
"name": "The Old Crown: Westgate St",
"value": "TOC:WS"
},
{
"name": "Miller and Carter: Olympus Park",
"value": "MAC:OP"
}
]
}
]
}