JQuery: How to loop an array of text
I'm wanting to loop an array of text. I was going to use .each() but I don't know if there is a way to do it with that. Is it possible or is there another way I need to do it? Thanks
I dont think it's necessary but here's what I was testing it with...
jQuery.each(data.reviews, function(index, itemData) {
var p = '"'+ itemData.review +'"';
$("#reviews p").text(p);
});
EDIT: It is an array of JSON objects. ( I think 开发者_开发技巧that's how you'd say it - or maybe - JSON Object of an array of objects )
By loop I'm wanting it to eventually fade in and out of each "review" and loop so if there is 5 reviews then it would loop from 5 to 0 then go back to 5 and continue infinitely. Hope that makes it more clear.
for (var i = 0; i < data.reviews.length; i++) {
$('#reviews p').text('"' + data.reviews[i].review + '"');
}
Not sure why you'd replace the #reviews p
text over and over, but native Javascript is fine for iterating arrays.
Not quite sure what you mean by "loop an array of text". Is it safe to assume data.reviews is a JSON object? if so, what you have should work, but you may want to use:
$('#reviews').append($('<p>').text('"'+itemData.review+'"'));
That would be in place of your current code in the .each
block. (this is assuming you're adding a new paragraph to #reviews for each entry. Your current method keeps replacing the contents of the paragraph with the very last entry found.)
JSFiddle sample: http://jsfiddle.net/HcV3P/
JSFiddle v2 -- with rotators: http://jsfiddle.net/HcV3P/2/
I think you should do it this way
data.reviews.each(function(index) {
//use $(this) to get the current review element
});
精彩评论