jquery动态表生成器

时间:2013-04-23 23:09:02

标签: javascript jquery

我使用jquery构建了非常简单的动态html表生成器,请检查以下内容......

<button id="addcolumn">Add Column</button>
<button id="addrow">Add Row</button>

<table width="100%" border="1" cellpadding="0" cellspacing="0">

<thead id="theads">
    <tr>
        <th class="th" contenteditable>Heading</th>
        <th class="th" contenteditable>Heading</th>
    </tr>
</thead>

<tbody id="tbody">

</tbody>

</table>

jquery的

$(document).ready(function () { 

    //add head
    $('#addcolumn').click(function(){
        $('<th class="th" contenteditable>Heading</th>').appendTo('thead tr');
    });

    //add row
    $('#addrow').click(function(){
        var totalths = $('.th').length;

        var trcon = '<tr>';
        for (var i = 0; i < totalths; i++) {
            var trcon = trcon + ' <td class="td" align="center" contenteditable>Content</td>';
        }
        var trcon = trcon + ' </tr>';

        $(trcon).appendTo('tbody');

    });

});

当前点击添加列按钮时添加th,点击添加行按钮添加行td = calculated numbers of th,其工作正常,但我正面临一个问题,假设我添加3列和2行3 tds,但如果我想在创建2行后添加更多列,它不会增加这些行中的tds。我希望你理解我的问题。谢谢。 try this in jsfiddle也是如此。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

$(document).ready(function () {
    var $cell = $('<td>', {
        'class': 'td',
        'align': 'center',
        'contenteditable': '',
        'text': 'Content'
    });

    var $header = $('<th>', {
        'class': 'th',
        'contenteditable': '',
        'text': 'Heading'
    });

    $('#addcolumn').click(function() {
        $header.clone().appendTo('thead tr');
        $cell.clone().appendTo('tbody tr');
    });

    $('#addrow').click(function(){
        var $row = $('<tr>');

        $('thead th').each(function() {
            $cell.clone().appendTo($row);
        });

        $row.appendTo('tbody');
    });
});

演示:http://jsfiddle.net/prBZS/4/

答案 1 :(得分:1)

在列添加按钮的事件处理程序中,只需向现有行添加一个单元格:

//add head
$('#addcolumn').click(function(){
  $('<th class="th" contenteditable>Heading</th>').appendTo('thead tr');
  $('<td class="td" align="center" contenteditable>Content</td>').appendTo('tbody tr');
});