jQuery-选择随机JSON对象 [英] Jquery - Select random JSON Object

查看:111
本文介绍了jQuery-选择随机JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个jquery代码,可以在页面加载时将条目输出到JSON文件中...

I have this jquery code to output the entries in a JSON file on page load...

$.getJSON('b.json', function(data) {
      $('#dictionary').empty().hide();



      $.each(data, function(entryIndex, entry) {
        var html = '<div class="entry">';
        html += '<h3 class="title">' + entry['title'] + '</h3>';
        html += '<div class="link_url">' + entry['link_url'] + '</div>';
        html += '<div class="image_src">';
        html += entry['image_src'];
        if (entry['quote']) {
          html += '<div class="quote">';
          $.each(entry['quote'], function(lineIndex, line) {
            html += '<div class="quote-line">' + line + '</div>';
          });
          if (entry['author']) {
            html += '<div class="quote-author">' + entry['author'] + '</div>';
          }
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';

        $('#dictionary').append(html).fadeIn();
      });
    });

我需要做的是随机加载这些条目之一.

What I need to do is load one of these entries, randomly.

任何建议表示赞赏.

非常感谢, C

JSON文件是...

The JSON file is...

[
  {
    "title": "WESITE NAME",
    "link_url": "http://www.website.com",
    "image_src": "http://www.website.com/images/recent.jpg",
  },
  {
    "title": "WESITE NAME",
    "link_url": "http://www.website.com",
    "image_src": "http://www.website.com/images/recent.jpg",
  },
  {
    "title": "WESITE NAME",
    "link_url": "http://www.website.com",
    "image_src": "http://www.website.com/images/recent.jpg",
  }
]

推荐答案

$.getJSON('b.json', function(data) { 
  var entry = data[Math.floor(Math.random()*data.length)];
  //do the same exact thing with entry
}

这篇关于jQuery-选择随机JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆