Javascript 使用jQuery循环随机JSON条目

Javascript 使用jQuery循环随机JSON条目,javascript,jquery,ajax,json,random,Javascript,Jquery,Ajax,Json,Random,我试图创建一个简单的抽认卡游戏,其中JSON文件中的人名列表(随机)循环,然后用户选择正确的人 我可以选择工作人员,但我似乎无法随机循环JSON文件。我已经看过了,但都没能去上班 这是JSFiddle: HTML: <div> <h3>Who is this?</h3> <div id="namesOutput"></div> </div> $(document).ready(function() {

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

我可以选择工作人员,但我似乎无法随机循环JSON文件。我已经看过了,但都没能去上班

这是JSFiddle:

HTML:

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

    <div id="namesOutput"></div>
</div>
$(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):

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

    <div id="namesOutput"></div>
</div>
$(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");

      }
    });
  });
});
$(文档).ready(函数(){
var=3;
//
//检索JSON
//
$.getJSON(“https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json,函数(结果){
var staffNumber=0;
var correctAnswer=“”;
var correctAnswerID=Math.floor((Math.random()*3)+1);
//环通集
$.each(结果、函数(i、字段){
staffNumber++;
if(staffNumber==correctAnswerID){
correctAnswer=field.name;
}
//输出可能的答案
$(“#名称输出”).append(“”+field.name+“”);
//根据级别断开循环
如果(员工人数===答案){
返回false;
}
});
//
//核对答案
//
$(“.gameBtn”)。单击(函数(e){
e、 预防默认值();
if($(this.attr('title')==correctAnswerID){
$(this.addClass(“btn--correct”);
$('.btn').not(“.btn--correct”).addClass(“btn--correct”);
}否则{
$(this.addClass(“btn——不正确”);
}
});
});
});

我会稍微改变一下它的工作方式。我不想在循环时获得随机索引,而是使用一种无序方法将项目添加到数组中,然后随机化它们的顺序

我添加了一个shuffle函数和一个objectsize函数,以使处理返回的数据更容易

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

      }
    });
  });
});
//由http://stackoverflow.com/a/6274381/648350
函数shuffle(o){//v1.0
对于(var j,x,i=o.length;i;j=Math.floor(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);
返回o;
};
//承蒙http://stackoverflow.com/a/6700/648350
Object.size=函数(obj){
变量大小=0,键;
用于(输入obj){
if(obj.hasOwnProperty(key))size++;
}
返回大小;
};
$(文档).ready(函数(){
var=3;
//
//检索JSON
//
$.getJSON(“https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json,函数(结果){
var numberOfResults=Object.size(结果);
var staffNumber=0;
var correctAnswer=“”;
var correctAnswerID=Math.floor((Math.random()*numberOfResults)+1);
var outputHtml=[];
//环通集
$.each(结果、函数(i、字段){
staffNumber++;
if(staffNumber==correctAnswerID){

correctAnswer='

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

我添加了一个shuffle函数和一个objectsize函数,以使处理返回的数据更容易

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

      }
    });
  });
});
//由http://stackoverflow.com/a/6274381/648350
函数shuffle(o){//v1.0
对于(var j,x,i=o.length;i;j=Math.floor(Math.random()*i),x=o[--i],o[i]=o[j],o[j]=x);
返回o;
};
//承蒙http://stackoverflow.com/a/6700/648350
Object.size=函数(obj){
变量大小=0,键;
用于(输入obj){
if(obj.hasOwnProperty(key))size++;
}
返回大小;
};
$(文档).ready(函数(){
var=3;
//
//检索JSON
//
$.getJSON(“https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json,函数(结果){
var numberOfResults=Object.size(结果);
var staffNumber=0;
var correctAnswer=“”;
var correctAnswerID=Math.floor((Math.random()*numberOfResults)+1);
var outputHtml=[];
//环通集
$.each(结果、函数(i、字段){
staffNumber++;
if(staffNumber==correctAnswerID){

correctAnswer='

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

我添加了一个shuffle函数和一个objectsize函数,以使处理返回的数据更容易

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

      }
    });
  });
});
/