简体   繁体   中英

Loop over random JSON entries using jQuery

I am trying to create a simple flashcard game where a list of people's names in a JSON file is looped over (randomly) and then the user selects which is the correct person.

I have the selecting of person working, but I cannot seem to randomly loop over the JSON file. I have looked here and here but have not been able to get either to work.

Here is the JSFiddle: http://jsfiddle.net/pacj02xq/1/

HTML:

<div>
    <h3>Who is this?</h3>

    <div id="namesOutput"></div>
</div>

JavaScript (jQuery):

$(document).ready(function() {
  var answers = 3;

  //
  // Retrieve JSON
  //
  $.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
    var staffNumber = 0;
    var correctAnswer = "";
    var correctAnswerID = Math.floor((Math.random() * 3) + 1);

    // Loop through set
    $.each(result, function(i, field) {
      staffNumber++;

      if (staffNumber == correctAnswerID) {
        correctAnswer = field.name;
      }

      // Output possible answers
      $("#namesOutput").append('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>');

      // Break loop depending on level
      if (staffNumber === answers) {
        return false;
      }
    });


    //
    // Check answer
    //
    $(".gameBtn").click(function(e) {
      e.preventDefault();

      if ($(this).attr('title') == correctAnswerID) {
        $(this).addClass("btn--correct");
        $('.btn').not(".btn--correct").addClass("btn--incorrect");
      } else {
        $(this).addClass("btn--incorrect");

      }
    });
  });
});

I would change the way this works slightly. Rather than get random indexes as you loop like you wanted, i would instead use a shuffle method to add items to an array, and then randomise their order.

I had added a shuffle function, and an object size function to make handling your returned data easier.

1) We loop over the results of the JSON get and store a random item as the correct answer, all the rest get added to an array.

2) We then shuffle the incorrect answers, and reduce the number of them to 1 less than the number of options you require

3) We then add the correct answer to the newly shortened list of incorrect answers, and shuffle them again

4) Lastly we flatten this array to a string and append it to the DOM.

// courtesy of http://stackoverflow.com/a/6274381/648350
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
// courtesy of http://stackoverflow.com/a/6700/648350
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};


$(document).ready(function() {
  var answers = 3;

  //
  // Retrieve JSON
  //
  $.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
    var numberOfResults = Object.size(result);
    var staffNumber = 0;
    var correctAnswer = "";
    var correctAnswerID = Math.floor((Math.random() * numberOfResults) + 1);
    var outputHtml = [];
    // Loop through set
    $.each(result, function(i, field) {
      staffNumber++;

      if (staffNumber == correctAnswerID) {
        correctAnswer = '<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'; // store our correct answer
      }else{
        outputHtml.push('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>'); // add all the other answers
      }
    });
    outputHtml = shuffle(outputHtml).slice(0, answers - 1); // -1 because one answer will come from the 'correct' answer
    outputHtml.push(correctAnswer); // add correct answer after slicing
    outputHtml = shuffle(outputHtml); // shuffle the correct answer around again
    outputHtml = outputHtml.join(''); // flatten outputHtml into single string
    $("#namesOutput").append(outputHtml); // add it to the DOM


    //
    // Check answer
    //
    $(".gameBtn").click(function(e) {
      e.preventDefault();

      if ($(this).attr('title') == correctAnswerID) {
        $(this).addClass("btn--correct");
        $('.btn').not(".btn--correct").addClass("btn--incorrect");
      } else {
        $(this).addClass("btn--incorrect");

      }
    });
  });
});

DEMO

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.

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