繁体   English   中英

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

[英]How to add column dynamically between first and last column of a table

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

 $('#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> 

我希望在“员工”和“必填”列之间添加新列。

请帮我

您总是在追加内容,这会将其作为最后一个td放在tr标记内,或作为另一个标记放在td标记内。 我的建议是插入新元素。 例如:

 $('#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">'))}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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