How to do test if a image is the first or the last of a group of images?
I'm trying to make previous and next buttons animate in or 开发者_开发百科out depending on whether I'm at the end of a series of images with the following code:
var $current = jQuery("img .active");
var $next = $current.next();
if ($next != jQuery("img:first-child")
{
// show next item and the previous button
// seems to work?
} else if ($next == jQuery("img:last-child")
{
// hide the next button since we're at the end
// doesn't seem to work??
}
You want to check the index of the img:
var $current = jQuery("#img .active"),
index = $current.index();
if (index === 0) {
// This is the first
} else if (index === jQuery("#img").children().length - 1) {
// This is the last
}
Assuming no big performance hit from using .each()
I would do something like this:
jQuery('#img').children().each(function(i,obj){
// some code to show buttons
if (i <= 0) { // hide prev }
if (i >= $('#img').children().length - 1) { // hide next }
});
Then hide all $('#img').children()
except for the active one, or however you want it to function.
精彩评论