loop through returned json using jquery
I am getting image and hyperlink information returned in the JSON. I'd like to use the cycle plugin if possible.
Example: [["1.jpg","http:\/\/www.this.net\/"],["2.jpg","http:\/\/www.that.net\/"],["3.jpg","http:\/\/www.what.com/l"]]
When my html page is first loaded it will already have this:
<div id="container"><a id="changeLink" href="o.html" target="_blank"><img id="changeImage" src="100.jpg" /></a>
Using the returned JSON, I'd like to loop through the image paths/links and update the changeLink and changeImage elements every 4 seconds. After it's reached the end, I'd like for it to repeat.
When page is loaded:
<a id="changeLink" href="http://www.this.net" target="_blank"><img id="changeImage" src="1.jpg" /></a>
After 4 seconds:
<a id="changeLink" href="http://www.that开发者_如何学Python.net" target="_blank"><img id="changeImage" src="2.jpg" /></a>
After 8 seconds:
<a id="changeLink" href="http://www.what.com" target="_blank"><img id="changeImage" src="3.jpg" /></a>
After 12 seconds:
<a id="changeLink" href="http://www.this.net" target="_blank"><img id="changeImage" src="1.jpg" /></a>
After 16 seconds:
<a id="changeLink" href="http://www.that.net" target="_blank"><img id="changeImage" src="2.jpg" /></a>
After 20 seconds:
<a id="changeLink" href="http://www.what.com" target="_blank"><img id="changeImage" src="3.jpg" /></a>
And so on.
It sounds like you would like to take the returned JSON, use it to generate <img>
elements in the DOM with the src
attibute pointing to the URLs in the JSON and then apply functionality to cycle through the images.
This can be achieved using, for example, the cycle plugin. Something like the following should work. Note: untested
$.getJSON('jsonArray.php', function(data){
var imgs = $.map(data, function (e, i) {
return $('<img>').attr('src', e[1] + e[0]);
});
$('#container-for-imgs')
.append(imgs)
.find('img')
.cycle({
fx: 'fade'
});
});
EDIT:
In response to the comment, I think you would like to do something like this. You will ned to be more specific if I have misinterpreted
$.getJSON('jsonArray.php', function(data){
var change = ['changeLink', 'changeImage'],
anchors = $.map(data, function (e, i) {
var anchor = $('<a target="_blank" >').attr('href', e[1]).attr('id', change[0] + i);
return $('<img>').attr('src', e[0]).attr('id', change[1] + i).appendTo(anchor);
});
$('#container-for-elements')
.append(anchors);
});
精彩评论