2017-03-03 46 views
0

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

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

我想 “雇员” 和 “强制” 列之间的新列。

请帮我

回答

0

你总是追加,这要么将其放在tr标签作为最后td,或内部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>

通知的变化。新newColtd元素被添加,与你的价值,这是你的第一列后插入:

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">'))} 
相关问题