Jquery动态表生成器

jquery dynamic table generator

本文关键字:动态 Jquery      更新时间:2023-09-26

我已经建立了一个非常简单的动态html表生成器使用jquery,检查以下…

<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。我希望你能理解我的问题。谢谢。

你可以这样做:

$(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/

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

//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');
});