【发布时间】:2011-07-05 23:42:55
【问题描述】:
我正在使用 jQuery 和 Flickr API 返回一个 json 对象,其中包含来自用户照片流的许多照片。
我想迭代生成的对象以最初显示 40 张照片,然后是“加载更多”按钮。每次单击该按钮时,下一批 40 张照片将附加到现有照片列表中。一旦对象中没有其他项目,该按钮将返回充当指向用户 Flickr 个人资料的超链接。
目前,我有显示前 40 张照片的工作代码。但是当单击“加载更多”按钮时,我会将所有剩余的项目添加到 HTML 中。这是因为我找不到产生上述行为的方法。
也许我也错过了一种更有效的方法。
这是我现有的代码。任何额外的 cmets 或改进都将受到欢迎。
$(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) {
});
};
【问题讨论】:
-
如果您不需要遍历其余条目api.jquery.com/eachjsfiddle.net/vj9JW
标签: javascript jquery json api flickr