2009-11-28 6 views
1

페이지로드시 JSON 파일의 항목을 출력하는 jquery 코드가 있습니다.Jquery - 임의의 JSON 객체 선택

$.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(); 
     }); 
    }); 

이 항목 중 하나를 무작위로로드하면됩니다.

어떤 조언을 부탁드립니다.

많은 감사합니다, C

JSON 파일은 ...

[ 
    { 
    "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", 
    } 
] 

답변

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

때 나는 경고() 항목의 변수가 나는 경고가 배열이나 객체를 처리 할 수 ​​있기 때문이다 [개체 개체] –

+0

를 얻을. Firefox 플러그인 Firebug를 사용해보고 console.log(); – PetersenDidIt

+0

'alert (entry.title);'을 시도하십시오. 여기서 title은 반환 된 JSON 객체의 속성입니다. –

1

보인다.

시도 :

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