开发者

Jquery - Select random JSON Object

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.

Any advice appreciated.

Man开发者_StackOverflow社区y thanks, C

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
}


Looks like you want a random entry from an array.

try:

var random_entry = entry[Math.floor(Math.random() * entry.length)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜