coolispaul
asked on
jquery each loop
Hi,
Im trying to create a function that manipulates an unorderd list and creates nested unorders lists with 10 list items in each.
My functyion so far looks like:
newlist variable gets lost on each iteration - any ideas why?
Thanks
Im trying to create a function that manipulates an unorderd list and creates nested unorders lists with 10 list items in each.
My functyion so far looks like:
$(".resources ul.book li").each(function(i, val) {
if(i%10==0) {
//$(this).append("<ul>");
var newlist = $("<ul>").insertAfter($(this));
}
if(newlist) {
newlist.append($(this));
}
i++;
});
newlist variable gets lost on each iteration - any ideas why?
Thanks
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You don't need the i++ - it automatically gets incremented with the each() call
Yep. FWIW, the value of "this" changes in the each loop as well. If you ever want to access "this" inside the each loop you have to do var saved_this = this outside of the loop.
'this' inside the each loop is the LI that you're on. You wouldn't have access to it outside the loop in the first place!
'this' outside the loop would refer to something else.
'this' outside the loop would refer to something else.
ASKER
thanks chris - yeah i was getting confused
By the way , mu function is now
but this produces:
<ul class="book">
<li><ul></ul>
<li><a href="">one</a></li>
<li><a href="">two</a></li>
</ul>
why is the ul in bold closed? i need the li to be inside the ul
Thanks
By the way , mu function is now
var newlist = '';
$(".resources ul.book li").each(function(i) {
if(i%10==0) {
newlist = $("<li><ul>").insertAfter($(this));
}
newlist.append($(this));
});
but this produces:
<ul class="book">
<li><ul></ul>
<li><a href="">one</a></li>
<li><a href="">two</a></li>
</ul>
why is the ul in bold closed? i need the li to be inside the ul
Thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
perfect thanks and thanks fo explaining why
ASKER
so variable scope is lost with the each() function because the function is effectively exited and entered again each time?
Thanks