PDA

View Full Version : jquery each function


C.O.D.E.N.A.M.E
04-03-2008, 03:09 PM
I am trying to iterate through a unordered list (jquery), but when I find the ninth element in this array (the LIs), I want to restart with i again from 0, that way item 0 and item 10 get the same class="menu_0", item 1 and item 11 get the same class="menu_1", and so on. I know I need another loop inside but how ...

This is what I got


jQuery(document).ready(

function(){
jQuery("#menu").find("li").each(function(i){
jQuery(this).addClass("menu_"+i);
jQuery(this).find("a").attr("rel","styles_"+i)
if (i==0)
jQuery("title").before("<link rel='stylesheet' type='text/css' href='styles_"+i+".css' title='styles_"+i+"' media='screen' />");
else
jQuery("title").before("<link rel='alternate stylesheet' type='text/css' href='styles_"+i+".css' title='styles_"+i+"' media='screen' />");



});

});

Thanks for any assistance!!

WA
04-03-2008, 10:36 PM
It looks like you're basically trying to extract the very last digit of i once it exceeds 9, and use that as the number added to "menu_"+x. If so, why not just do something like:

jQuery("#menu").find("li").each(function(i){
var strindex=i.toString()
var classindex=strindex.charAt(strindex.length-1)
jQuery(this).addClass("menu_"+classindex);
"
"

You can see the effect of this more readily with a test case:

<script type="text/javascript">

for (var i=0; i<30; i++){
var strindex=i.toString()
var classindex=strindex.charAt(strindex.length-1)
document.write(classindex+'<br />')
}

</script>

C.O.D.E.N.A.M.E
04-09-2008, 09:56 AM
Thanks for your help!

I got one more issue though. How do I iterate through let's say 30 list items
and give 'm menu_0 till menu_8 and count back from 0 till 8 without using menu_9,

0 1 2 3 4 5 6 7 8 0 (first 10 list items)
0 1 2 3 4 5 6 7 8 0
0 1 2 3 4 5 6 7 8 0