views:

63

answers:

2
+1  Q: 

For loop in jQuery

Need to run a for loop in jquery. Condition is :

i have the following code

<div id="container">
  <ul>
    <li style="background-color:#CCC">First</li>
    <li style="background-color:#CCC">Second</li>
    <li style="background-color:#CCC">Third</li>
    <li style="background-color:#CCC">Fourth</li>
    <li style="background-color:#999">Fifth</li>
    <li style="background-color:#666">Sicth</li>
    <li style="background-color:#000; color:#FFF;">Seventh</li>
    <li style="background-color:#000; color:#FFF;">Eighth</li>
  </ul>
</div>    

<script type="text/javascript">
    $(document).ready(function(){
        var w = 0;
        var bpl=7;
        var tw = 960;
        var cal_width =0;
        var lines =0;
        w = $('li').size();
        cal_width = (tw/w)-30 + "px";
        lines = Math.floor(w/bpl) + (w%bpl>0 ? 1 : 0);
        $("#container").each(function(lines){
            //$("ul > li").css({"width": cal_width});
        });
    });
</script>    
  1. var lines = 2;
  2. for loop will run to the number of lines i.e. 2 times
  3. there are 7 LI items under UL
  4. as an when the LI count goes to 8 items, need to generate a second UL and 8th LI item
    will appear as a part of second UL.

so as an when more than 7 items comes then a seperate UL will wrap those LI items.

Please help!

A: 

why not you do like this (if any specific reason, please let me know)-

1. Open first UL
2. Do Creat Li until reach to limit // here 7
3. Close first UL 
4. Open second UL
5. Creat Li
6. Close second UL
Sadat
i got your point Sadat, can you write down the code so that even i can understand how to implement for loop in this particular scenario.Please help me with the code if possible.
Lokesh
+2  A: 
var container = $("#container");
var lis = $("ul > li", container);
var ul;

container.empty();

for (var i = 0, l = lis.length; i < l; i ++) {
    if (i % 7 == 0) ul = $("<ul />").appendTo(container);
    $(lis[i]).appendTo(ul);
}
fantactuka
thanks a lot Fantactuka. Your code helped me a lot in achieving the final result.Thanks a lot once again.
Lokesh