如何在表的第一列和最后一列之间动态添加列

阿皮特·古普塔

我已经开发了一个表格,我可以动态添加行和列。但问题是我想在表格的第一列和最后一列之间添加列,因为新列只在最后添加。

$('#irow').click(function(){
    if($('#row').val()){
        $('#mtable tbody').append('<tr><td>Some Item</td></tr>');
        $('#mtable tbody tr:last td:first').html($('#row').val());
    }else{alert('Enter Text');}
});
$('#icol').click(function(){
    if($('#col').val()){
        $('#mtable tr').append($("<td>"));
        $('#mtable thead tr>td:last').html($('#col').val());
        $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))});
    }else{alert('Enter Text');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<table border="1" id="mtable" class="table table-striped table-hover individual">
    <thead><tr><td>Employee \department</td><td>Mandatory</td></tr></thead>
    <tbody></tbody>
</table><br/><br/>
<input id="row" placeholder="Enter Employee Name"/><button id="irow">Add Board</button><br/><br/>
<input id="col" placeholder="Enter department Name"/><button id="icol">Add Subject</button>

我想要“雇员”和“必填”列之间的新列。

请帮我

阿明

您总是在追加,这将把它tr作为 lasttd放在tdtag内,或者作为另一个 tag放在tag我的建议是插入新元素。例如:

$('#irow').click(function(){
    if($('#row').val()){
        $('#mtable tbody').append('<tr><td>Some Item</td></tr>');
        $('#mtable tbody tr:last td:first').html($('#row').val());
    }else{alert('Enter Text');}
});
$('#icol').click(function(){
    if($('#col').val()){
        var newCol = jQuery('<td/>', {
            text: $('#col').val()
        }).insertAfter('#mtable thead tr td:first');

        $('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))});
    }else{alert('Enter Text');}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="mtable" class="table table-striped table-hover individual">
    <thead><tr><td>Employee \department</td><td>Mandatory</td></tr></thead>
    <tbody></tbody>
</table><br/><br/>
<input id="row" placeholder="Enter Employee Name"/><button id="irow">Add Board</button><br/><br/>
<input id="col" placeholder="Enter department Name"/><button id="icol">Add Subject</button>

注意变化。newCol td添加了带有您的值的元素,并将其插入到您的第一列之后:

if($('#col').val()){
    var newCol = jQuery('<td/>', {
        text: $('#col').val()
    }).insertAfter('#mtable thead tr td:first');

此外,如果您想颠倒顺序,您可以切换到:

.insertBefore('#mtable thead tr td:last');

这将在最后一列之前添加新列。你应该用这段代码解释你想要什么:

$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="text">'))}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章