I'm trying to make a quiz application using JQuery, JSON, and Mustache.js, but I'm having some trouble.
I can get Mustache.js to print out my entire set of JSON objects, no problem, but I'm wondering if there's a way I can get it to only print out one set of objects at a time. For instance, I would like the quiz app to display one question and its corresponding set of possible answers (in radio button form), then when a user selects an answer and presses the "next" button, the next question and set of answers will appear and replace the previous answers.
As it stands, I currently have JQuery making an AJAX call to my json file, and mustache.js pulling all records in and displaying them in a series of p tags (for the questions) and ul tags (for the answers). So for now, is there some way I can get it to only grab one question at a time?
Here is what I currently have in my script. Please note, this is a work in progress.
$(function(){
$.getJSON('data.json', function(data){ //Make AJAX call to server
var template = "{{#quiz}}" + //Create mustashe js template
"<div class='quizarea'>" +
"<p>{{question}}</p>" +
"<ul>" +
"{{#answers}}" +
"<li>{{text}}</li>" +
"{{/answers}}" +
"</ul>" +
"</div>" +
"{{/quiz}}";
var html = Mustache.to_html(template, data);//Turn template into usable html
$('#quizpane').html(html);//Send html to the quizpane div
});//get JSON
});//end function
The example can be found at http://jamesdauer.com/javascript/quiz/
Maybe Mustache.js isn't even the way to go? I was thinking I might try and use handlebars or ember, but I don't know that those would do what I'm looking to do any better. I really appreciate any help you folks can give. Thanks!
First a few changes to your code should be made. 1. The javascript:
$(function () {
var template = "<div class='quizarea'>" +
"<p>{{question}}</p>" +
"<ul>" +
"{{#answers}}" +
"<li>{{text}}</li>" +
"{{/answers}}" +
"</ul>" +
"</div>";
var count = 0;
render = function () {
var html = Mustache.to_html(template, data.quiz[count]);
$('#quizpane').html(html);
};
render();
$("#next-question").click(function () {
count++;
render();
});
});
2 . In the HTML :
<div id='quizpane'></div>
<button name="next" id="next-question">Next question</button>
note that the I changed the template and added a counter to the javascript to keep track at which question you are currently, and instead of sending the entire data
object to render()
you sent the current question data.quiz[count]
On fiddle: http://jsfiddle.net/aBNVJ/1/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.