。每()找到的最后一个项目,并创建一个if语句
我有以下的jQuery,。每()找到的最后一个项目,并创建一个if语句
function animTweets($tweets) {
$tweets.each(function() {
var $tweet = $(this);
$('#twitterTile').queue('myQueue', function (next) {
$tweet.animate({top: 0, height: 'show'},
{duration: 300,
queue: false,
complete: next
});
}).delay(1E10, 'myQueue');
});
}
它通过包含在一个列表($微博)的项目进行迭代。
如何创建if
语句以使最后一项具有不同的动画?
function animTweets($tweets) {
var len = $tweets.length;
var count = 1;
$tweets.each(function() {
var $tweet = $(this);
if(len == count){
//different anim
}else{
$('#twitterTile').queue('myQueue', function (next) {
$tweet.animate({top: 0, height: 'show'},
{duration: 300,
queue: false,
complete: next
});
}).delay(1E10, 'myQueue');
}
count++;
});
}
你可以得到使用.length
然后鸣叫总数对证使用index
是.each()
公开检查,如果当前index
是最后一个:
function animTweets($tweets) {
var total = $tweets.length;
$tweets.each(function (index, obj) {
var $tweet = $(this);
if ((index + 1) == total) {
//this is the last one
} else {
$('#twitterTile').queue('myQueue', function (next) {
$tweet.animate({top: 0, height: 'show'},
{duration: 300,
queue: false,
complete: next
});
}).delay(1E10, 'myQueue');
}
});
}
Google文档.each()
: http://api.jquery.com/each
不应该索引总数为1? – 2011-12-20 22:38:39
@ZacharyBurt良好的捕获,'index'从零开始,'.length'从一开始。 – Jasper 2011-12-20 22:40:17
$tweets.each(function (index) {
if(index == $tweets.length-1) {
//special behavior
}
});
不妨缓存'$ tweets.length'的值,因为它可能会被多次使用。 – Jasper 2011-12-20 22:40:59
如何使用.slice()
[docs]和.last()
[docs]:
$tweets.slice(0, -1).each(...);
var $lastTweet = $tweets.last();
// do something with the last tweet.
有时候我们忘记了.each()
并不总是比一个好,老式for
循环更好,因为我们失去对循环控制。假设参数animTweets是jQuery对象,你可以使用for
循环是这样的:
function animTweets($tweets) {
var $tweet;
for (var i = 0, len = $tweets.length - 1; i < len; i++) {
$tweet = $tweets.eq(i);
$('#twitterTile').queue('myQueue', function (next) {
$tweet.animate({top: 0, height: 'show'},
{duration: 300,
queue: false,
complete: next
});
}).delay(1E10, 'myQueue');
}
// now process the last one separately
tweet$ = $tweets.eq(-1);
// ...
}
'$ tweet = $ tweets.eq(i);'比$ tweet = $(tweets [i])更清洁一些;'IMO。 – 2011-12-20 23:07:51
我说我假设推文是一组元素。它没有在他们的问题中说明究竟是什么。如果它是一个带有元素的jQuery对象,那么我会同意你的建议。 – jfriend00 2011-12-20 23:15:51
哦,对不起,我只是在文本上剔除;)但如果'$ tweets'是一个正常的数组,'$ tweets.each'会抛出一个错误。 – 2011-12-20 23:17:07
权,使用指数甚至更好,当然。 – 2011-12-20 22:39:44