getting index of an li in a ul?
I'm close to this but cross-brained on something.
I have this code:
var numOfLi = $('#myList li').length;
var lastLi = numOfLi;
$('.next').click(function() {
var current = $('#myList').find('li.on');
current.removeClass('on');
current.next().addClass('on');
var grabAlt = $('.on img').attr('alt').split('|');
var holdAlt = grabAlt;
$('#altStuff').html('<ul class="altDescription">' +
'<li>' + holdAlt[0] + '</li>' + '<li>' + holdAlt[1] +
'</li>' + '<li>' + holdAlt[2] + '</li>' + '</ul>');
});
$('.prev').click(function() {
var current = $('#myList').find('li.on');
current.removeClass('on');
current.prev().addClass('on');
var grabAlt = $('.on img').attr('alt').split('|');
var holdAlt = grabAlt;
$('#altStuff').html('<ul class="altDescription">' +
'<li>' + holdAlt[0] + '</li>' + '<li>' + holdAlt[1] +
'</li>' + '<li>' + holdAlt[2] + '</li>' + '</ul>');
});
It clicks forward and back through a list of Li's, assigns a class of 'on' to the li, grabs the alt text of the image in each Li, parses that and puts it into a paragraph.
This all works great and dynamically, but now I'm trying to stop the next/prev buttons when they reach the first/last li.
My thought is to: 1. upon clicking, check to see if the current 开发者_如何转开发li is the first one (don't let prev work) or the last one (don't let next work).
But, I'm a little mushed now as to how to check that. The .length only returns the count....so, how can I get the position value of whatever the current li is?
I was thinking I have to put all the li's of this ul into a matrix and then just check against it's index but I'm not getting that work.
Thanks for looking.
I was thinking I'd have to put the entire UL list into
$('li.on').index()
will give you the position of that li
within it's parent.
The [almost] absolute laziest, and not necessarily easiest, would be to keep track of which li
you're on.
You already get the length, so you know that the last li
would have an index of numOfLi - 1
, and you know that the first li
would have an index of 0.
So you could change it to something like this:
var numOfLi = $('#myList li').length;
var lastLi = numOfLi - 1;
var currentLi = 0; // I think? This wasn't clear.
$('.next').click(function () {
if (currentLi !== lastLi) {
currentLi += 1;
// ...
}
});
$('.prev').click(function () {
if (currentLi) {
currentLi -= 1;
// ...
}
});
精彩评论