2017-03-03 90 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">'))} 
相關問題