javascript - Pull a single item from json and display in html -
i have array in json file , want pull single entry array , display when page loads. have gotten partway there using this question , answer, attempt adapt answer causes output html block repeat array items in sequence instead of picking one.
here screenshot of get: screenshot of output
i doing real stupid, , hope can point out. script follows:
$.getjson('recommend.json', function(data) { var entry = data[math.floor(math.random()*data.length)]; $.each(data, function(entryindex, entry) { var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>'; html += '<span class="rec_title">' + entry['title'] + '</span><p>'; html += '<span class="rec_author">' + entry['author'] + '</span><p>'; html += '<span class="rec_blurb">' + entry['blurb'] + '</span>'; $('#recblock').append(html).fadein(); }); });
any questions let me know.
cut this:
$.each(data, function(entryindex, entry) {
the whole purpose of $.each
iterate on entire array, opposite of want. you're defining entry
earlier random entry data.
so you'll have:
$.getjson('recommend.json', function(data) { var entry = data[math.floor(math.random()*data.length)]; var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>'; html += '<span class="rec_title">' + entry['title'] + '</span><p>'; html += '<span class="rec_author">' + entry['author'] + '</span><p>'; html += '<span class="rec_blurb">' + entry['blurb'] + '</span>'; $('#recblock').append(html).fadein(); });
Comments
Post a Comment