簡體   English   中英

使用jQuery遍歷隨機JSON條目

[英]Loop over random JSON entries using jQuery

我正在嘗試創建一個簡單的抽認卡游戲,其中將JSON文件中的人的名字列表循環(隨機),然后用戶選擇哪個人是正確的人。

我可以選擇要工作的人,但是似乎無法隨機循環JSON文件。 我看過這里這里,但都無法工作。

這是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");

      }
    });
  });
});

我會稍微改變它的工作方式。 而不是像您想要的那樣在您循環時獲取隨機索引,而是使用shuffle方法將項目添加到數組,然后隨機化它們的順序。

我添加了隨機播放功能和對象大小功能,以更輕松地處理返回的數據。

1)我們遍歷JSON get的結果,並將隨機項存儲為正確答案,所有其余項都添加到數組中。

2)然后我們將不正確的答案打亂,並將其數量減少到少於您所需選項的數量1

3)然后,我們將正確答案添加到新近縮短的錯誤答案列表中,並再次隨機播放

4)最后,我們將此數組展平為一個字符串,並將其附加到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");

      }
    });
  });
});

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM