[英]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.