开发者

alternate row table in jquery

开发者 https://www.devze.com 2023-01-12 16:41 出处:网络
How to create below mentioned table structure in jquery/javascript: <table> <tr> <td> one

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

  <table>
    <tr>
        <td>
            one
        </td>
        <td&开发者_开发知识库gt;
            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>

i.e. 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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号