简体   繁体   中英

alternate row table in jquery

How to create below mentioned table structure in jquery/javascript:

  <table>
    <tr>
        <td>
            one
        </td>
        <td>
            two
        </td>
        <td>
            three
        </td>
    </tr>
    <tr>
        <td>
           single
        </td>

    </tr>
      <tr>
        <td>
            one
        </td>
        <td>
            two
        </td>
        <td>
            three
        </td>
    </tr>
     <tr>
        <td>
           single
        </td>

    </tr>
</table>

ie alternate row is having 3/ 1 cols.

This should suffice:

$(document).ready(function(){
    var $myTable = $("<table></table>");
    var $myRow;
    var rowCount = 10; //or whatever you want
    var cellCount = 1;
    var i = 0;
    for (i=0; i<rowCount; i++){
        $myRow = $("<tr></tr>");
        cellCount = (i%2 === 0)? 3 : 1;

        for (var j=0; j<cellCount; j++){
           $myRow.append("<td>a</td>") 
        }

        $myTable.append($myRow);
    }

    $("body").append($myTable); //if you want to add it to your document.
});​

Check out the JSFiddle: http://jsfiddle.net/ZbJ3v/

This, of course doesn't add in your "one" "two", etc (I just have 'a' to denote the structure) but I assumed from your question that you just wanted the structure.

Edit for comment below . The loop block would look something like:

    for (i=0; i<rowCount; i++){
        $myRow = $("<tr></tr>");
        if (i%2 === 0){
           $myRow.append("<td>aa.bb</td>") 
           $myRow.append("<td>aa.cc</td>") 
           $myRow.append("<td>aa.dd</td>") 
        }else{
           $myRow.append("<td>xx</td>") 
        }

        $myTable.append($myRow);
    }

Avaliable on this jsfiddle: http://jsfiddle.net/WPJ5q/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM