我使用jQuery和Flickr API來返回包含用戶照片流中的許多照片的json對象。如何部分和漸進地遍歷JavaScript對象?
我想遍歷結果對象最初顯示40張照片,然後是「加載更多」按鈕。每次點擊該按鈕時,下一批40張照片將被添加到現有照片列表中。一旦對象中沒有其他項目,該按鈕就會回到用戶的Flickr配置文件的超鏈接。
目前,我有工作代碼,顯示前40張照片。但是當單擊「加載更多」按鈕時,我將所有剩餘的項目添加到HTML中。這是因爲我無法找到一種方法來產生上述那種行爲。
也許有一種更有效的方法,我也錯過了。
這是我現有的代碼。任何其他意見或改進將是最受歡迎的。
$(function() {
myApp.uri = myApp.flickrUrl + '&per_page=' + myApp.maxNum + '&api_key=' + myApp.flickrApiKey + '&user_id=' + myApp.flickrUserId;
myApp.getPhotos(myApp.uri, myApp.callback);
});
var myApp = {
flickrApiKey : 'xxxx',
flickrUserId : 'xxxx',
flickrUrl : 'http://api.flickr.com/services/rest/?format=json&extras=url_t&method=flickr.people.getPublicPhotos',
callback : 'jsonFlickrApi',
minNum : 40,
maxNum : 500
};
myApp.getPhotos = function (u, c) {
var jxhr = $.ajax({
dataType : 'jsonp',
url : u,
jsonpCallback : c,
timeout : 5000
})
.success(function (data, status) {
var photosContainer = $('#photos');
photosContainer.prepend('<ul/>');
var photosList = $('#photos ul');
// while there are more photos to load, the default link text
// is replaced with a string stored in a data-* attribute
var moreLink = $('#more');
var moreLinkText = moreLink.text();
var moreLinkTextJs = moreLink.attr('data-text-js');
moreLink
.attr('data-text-nojs', moreLinkText)
.text(moreLinkTextJs)
.insertAfter(photosContainer);
// initially populate the Photo List with the first 40 photos
$.each(data.photos.photo, function (i, item){
if (i < myApp.minNum) {
var photoEl = '<li><a href="' + 'http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank"><img src="' + item.url_s + '" alt="' + item.title + '"></a></li>';
$(photoEl).appendTo(photosList);
}
});
// click on "More" link loads in all remaining photos.
// would like this to load the next 40 in the object
// each click until there are no items left...at which point unbind
moreLink.live('click', function (e) {
e.preventDefault();
$.each(data.photos.photo, function (i, item){
if (i >= myApp.minNum) {
var photoEl = '<li><a href="' + 'http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank"><img src="' + item.url_s + '" alt="' + item.title + '"></a></li>';
$(photoEl).appendTo(photosList);
}
});
// unbind events and revert the link text
moreLink.text(moreLinkText).blur().die();
});
})
.error(function (status) {
});
};
東西,你可以做些什麼來幫助與性能,如果你不需要遍歷條目http://api.jquery.com/each/ HTTP其餘逃脫你的循環://的jsfiddle。 net/vj9JW/ – stanwilsonjr 2011-02-28 21:46:41
感謝您的指針 – user638118 2011-02-28 23:05:23