【问题标题】:Loop over random JSON entries using jQuery使用 jQuery 循环遍历随机 JSON 条目
【发布时间】:2015-01-22 21:35:41
【问题描述】:

我正在尝试创建一个简单的抽认卡游戏,其中一个 JSON 文件中的人名列表被循环(随机),然后用户选择哪个是正确的人。

我选择了工作人员,但我似乎无法随机遍历 JSON 文件。我看过herehere 但都无法工作。

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

      }
    });
  });
});

【问题讨论】:

    标签: javascript jquery ajax json random


    【解决方案1】:

    我会稍微改变它的工作方式。我不会像你想要的那样循环获取随机索引,而是使用 shuffle 方法将项目添加到数组中,然后随机化它们的顺序。

    我添加了一个随机播放函数和一个对象大小函数,以便更轻松地处理您返回的数据。

    1) 我们遍历 JSON 获取的结果并存储一个随机项作为正确答案,其余的都添加到一个数组中。

    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");
    
          }
        });
      });
    });
    

    DEMO

    【讨论】:

      猜你喜欢
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      相关资源
      最近更新 更多