I'm trying to pull a set of images from flickr:
<ul class="thumb">
<li>
<p class="artisan-name">item.title</p> 开发者_开发知识库
<img src="item.photo">
</li>
..... as many li's as there are photos in the set
</ul>
So far, I have the photos wrapped in the li, but I cannot figure out for the life of me how to get the p to come before the img within the ul.
what I have so far:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photoset.gne?set=72157623815188370&
nsid=12295778@N08&lang=en-us&format=json&jsoncallback=?", function(data){
$.each(data.items, function(i,item){
$("#title").html(item.title);
$("<img/>").attr("src", item.media.m).appendTo("ul.thumb")
.wrap("<li>");
});
});
});
</script>
<ul class="thumb"></ul>
var listItems = '';
$.each(data.items, function(i,item){
// construct the html string
// do NOT manipulate DOM inside a loop
// it's to costly
listItems
+= '<li>'+
'<p class="artisan-name">'+item.title+'</p>'+
'<img src="'+item.media.m+'" />'+
'</li>';
});
// manipulate the DOM only once
// to add all the li elements
$('ul.thumb').append(listItems);
Update: Here is the complete code (comments removed)
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photoset.gne?set=72157623815188370&nsid=12295778@N08&lang=en-us&format=json&jsoncallback=?", function(data){
var listItems = '';
$.each(data.items, function(i,item){
listItems
+= '<li>'+
'<p class="artisan-name">'+item.title+'</p>'+
'<img src="'+item.media.m+'" />'+
'</li>';
});
$('ul.thumb').append(listItems);
});
});
Use:
$.each(data.items, function(i,item){
$("#title").html(item.title);
var liElem=$('<li/>').append('<p>'+item.title+'</p>');
$("<img/>").attr("src", item.media.m).appendTo(liElem);
liElem.appendTo("ul.thumb");
});
For better performances:
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("http://api.flickr.com/services/feeds/photoset.gne?set=72157623815188370&
nsid=12295778@N08&lang=en-us&format=json&jsoncallback=?", function(data){
if(data.items && data.items.length){
var arrLength=data.items.length,v='',dataHtml='';
for(var i=0;i<arrLength;++i){
v=data.items[i];
if(v.media && v.media.m) dataHtml+='<li><p>'+(v.title||'')+'</p><img src="'+v.media.m+'" alt=""/></li>';
}
$('ul.thumb').append(dataHtml);
}
});
});
</script>
精彩评论