jQuery appendメソッドを使ってテーブルに行を追加するサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
$('テーブルのクラス名’).append('<tr><td>’ + 値1 + '</td><td>値2</td></tr>’);
appendメソッドを使ってテーブルを追加します。
使用例
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function(){
//tr要素をカウント
var cnt= $('.cft tr').length;
$('#btnchg').click(function(e){
//テーブルを追加する
$('.cft').append('<tr><td>' + (++cnt) + '</td><td>項目</td></tr>');
});
})
</script>
</head>
<body>
<table style="width:60%" class="cft">
<tr>
<td>1</td>
<td>東京</td>
</tr>
<tr>
<td>2</td>
<td>大阪</td>
</tr>
</table>
<p>
<button id="btnchg" >実行</button></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function(){
//tr要素をカウント
var cnt= $('.cft tr').length;
$('#btnchg').click(function(e){
//テーブルを追加する
$('.cft').append('<tr><td>' + (++cnt) + '</td><td>項目</td></tr>');
});
})
</script>
</head>
<body>
<table style="width:60%" class="cft">
<tr>
<td>1</td>
<td>東京</td>
</tr>
<tr>
<td>2</td>
<td>大阪</td>
</tr>
</table>
<p>
<button id="btnchg" >実行</button></p>
</body>
</html>
<!DOCTYPE html> <html> <head> <style> table, th, td { border:1px solid black; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function(){ //tr要素をカウント var cnt= $('.cft tr').length; $('#btnchg').click(function(e){ //テーブルを追加する $('.cft').append('<tr><td>' + (++cnt) + '</td><td>項目</td></tr>'); }); }) </script> </head> <body> <table style="width:60%" class="cft"> <tr> <td>1</td> <td>東京</td> </tr> <tr> <td>2</td> <td>大阪</td> </tr> </table> <p> <button id="btnchg" >実行</button></p> </body> </html>
実行結果
「実行」ボタンを押すと、テーブルを追加します。