2017-03-03 5 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

あなたが常に追加され、最後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>

は変化に注目してください。新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">'))} 
関連する問題