Add a class via for-loop
I have a very simple for-loop in jQuery:
var iEra;
for(iEra = 1; iEra <= li.length; iEra++) {
li.addClass(iEra);
}
li is a variable targeting $('ul.class li') objects. iEra is the counter variable that should start from 1 up to the number of li objects present.
The main issue is that the function addClass is not happening at all. However if I replace it by, for example, alert(iEra);, I will get my 1-x alerts.
I know I could modify my for-loop to be a "constructor", like so:
var iEra;
for(iEra = 1; iEra <= li.le开发者_开发百科ngth; iEra++) {
parentOfli.append('<li class=" + iEra + "></li>');
}
That way I would get my classes 1-x added just fine. Problem is, those li objects are already being generated somewhere else.
I hope I explained myself thoroughly; if not, please let me know so! Live example: http://jsfiddle.net/c3cXB/9/
Class names cannot be a number.
Here is one that works: http://jsfiddle.net/c3cXB/10/
var li = $('ul.portfolio-excerpt').find('li');
var iEra, thumbLi = $('.thumbs ul li');
for (iEra = 1; iEra <= li.length; iEra++) {
thumbLi.eq(iEra).addClass('class'+iEra);
}
If you really need a loop
$('.thumbs ul li').each(function(index) {
$(this).addClass(iEra);
}
Or this way, if you just want to add a class to all of the Li
$('.thumbs ul li').addClass(iEra);
I'm not sure what's wrong with your example, I had to change css to 'li.thumbs' to see the following is working:
var $thumbLi = $('.thumbs ul li')
$('ul.portfolio-excerpt li:lt(' + $thumbLi.length + ')').addClass('thumbs');
See also http://api.jquery.com/lt-selector/
精彩评论